blob: 003005a8e6294247df3d5bbea887a54ccd365cd7 [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>
dchenge48600452015-12-28 02:24:5011#include <utility>
[email protected]e5ffd0e42009-09-11 21:30:5612
shessc9e80ae22015-08-12 21:39:1113#include "base/bind.h"
shessc8cd2a162015-10-22 20:30:4614#include "base/debug/dump_without_crashing.h"
[email protected]57999812013-02-24 05:40:5215#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4416#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4617#include "base/format_macros.h"
18#include "base/json/json_file_value_serializer.h"
[email protected]a7ec1292013-07-22 22:02:1819#include "base/lazy_instance.h"
[email protected]e5ffd0e42009-09-11 21:30:5620#include "base/logging.h"
shessc9e80ae22015-08-12 21:39:1121#include "base/message_loop/message_loop.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5022#include "base/metrics/histogram.h"
[email protected]210ce0af2013-05-15 09:10:3923#include "base/metrics/sparse_histogram.h"
[email protected]80abf152013-05-22 12:42:4224#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1925#include "base/strings/string_util.h"
26#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4527#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1828#include "base/synchronization/lock.h"
ssid9f8022f2015-10-12 17:49:0329#include "base/trace_event/memory_dump_manager.h"
ssid3be5b1ec2016-01-13 14:21:5730#include "sql/connection_memory_dump_provider.h"
shess9bf2c672015-12-18 01:18:0831#include "sql/meta_table.h"
[email protected]f0a54b22011-07-19 18:40:2132#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0333#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5634
[email protected]2e1cee762013-07-09 14:40:0035#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
36#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
37#endif
38
[email protected]5b96f3772010-09-28 16:30:5739namespace {
40
41// Spin for up to a second waiting for the lock to clear when setting
42// up the database.
43// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2744const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5745
46class ScopedBusyTimeout {
47 public:
48 explicit ScopedBusyTimeout(sqlite3* db)
49 : db_(db) {
50 }
51 ~ScopedBusyTimeout() {
52 sqlite3_busy_timeout(db_, 0);
53 }
54
55 int SetTimeout(base::TimeDelta timeout) {
56 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
57 return sqlite3_busy_timeout(db_,
58 static_cast<int>(timeout.InMilliseconds()));
59 }
60
61 private:
62 sqlite3* db_;
63};
64
[email protected]6d42f152012-11-10 00:38:2465// Helper to "safely" enable writable_schema. No error checking
66// because it is reasonable to just forge ahead in case of an error.
67// If turning it on fails, then most likely nothing will work, whereas
68// if turning it off fails, it only matters if some code attempts to
69// continue working with the database and tries to modify the
70// sqlite_master table (none of our code does this).
71class ScopedWritableSchema {
72 public:
73 explicit ScopedWritableSchema(sqlite3* db)
74 : db_(db) {
75 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
76 }
77 ~ScopedWritableSchema() {
78 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
79 }
80
81 private:
82 sqlite3* db_;
83};
84
[email protected]7bae5742013-07-10 20:46:1685// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
86// SQLite error code from running the backup step.
87int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
88 DCHECK_NE(src, dst);
89 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
90 if (!backup) {
91 // Since this call only sets things up, this indicates a gross
92 // error in SQLite.
93 DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
94 return sqlite3_errcode(dst);
95 }
96
97 // -1 backs up the entire database.
98 int rc = sqlite3_backup_step(backup, -1);
99 int pages = sqlite3_backup_pagecount(backup);
100 sqlite3_backup_finish(backup);
101
102 // If successful, exactly one page should have been backed up. If
103 // this breaks, check this function to make sure assumptions aren't
104 // being broken.
105 if (rc == SQLITE_DONE)
106 DCHECK_EQ(pages, 1);
107
108 return rc;
109}
110
[email protected]8d409412013-07-19 18:25:30111// Be very strict on attachment point. SQLite can handle a much wider
112// character set with appropriate quoting, but Chromium code should
113// just use clean names to start with.
114bool ValidAttachmentPoint(const char* attachment_point) {
115 for (size_t i = 0; attachment_point[i]; ++i) {
116 if (!((attachment_point[i] >= '0' && attachment_point[i] <= '9') ||
117 (attachment_point[i] >= 'a' && attachment_point[i] <= 'z') ||
118 (attachment_point[i] >= 'A' && attachment_point[i] <= 'Z') ||
119 attachment_point[i] == '_')) {
120 return false;
121 }
122 }
123 return true;
124}
125
shessc9e80ae22015-08-12 21:39:11126void RecordSqliteMemory10Min() {
avi0b519202015-12-21 07:25:19127 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11128 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.TenMinutes", used / 1024);
129}
130
131void RecordSqliteMemoryHour() {
avi0b519202015-12-21 07:25:19132 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11133 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneHour", used / 1024);
134}
135
136void RecordSqliteMemoryDay() {
avi0b519202015-12-21 07:25:19137 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11138 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneDay", used / 1024);
139}
140
shess2d48e942015-08-25 17:39:51141void RecordSqliteMemoryWeek() {
avi0b519202015-12-21 07:25:19142 const int64_t used = sqlite3_memory_used();
shess2d48e942015-08-25 17:39:51143 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneWeek", used / 1024);
144}
145
[email protected]a7ec1292013-07-22 22:02:18146// SQLite automatically calls sqlite3_initialize() lazily, but
147// sqlite3_initialize() uses double-checked locking and thus can have
148// data races.
149//
150// TODO(shess): Another alternative would be to have
151// sqlite3_initialize() called as part of process bring-up. If this
152// is changed, remove the dynamic_annotations dependency in sql.gyp.
153base::LazyInstance<base::Lock>::Leaky
154 g_sqlite_init_lock = LAZY_INSTANCE_INITIALIZER;
155void InitializeSqlite() {
156 base::AutoLock lock(g_sqlite_init_lock.Get());
shessc9e80ae22015-08-12 21:39:11157 static bool first_call = true;
158 if (first_call) {
159 sqlite3_initialize();
160
161 // Schedule callback to record memory footprint histograms at 10m, 1h, and
162 // 1d. There may not be a message loop in tests.
163 if (base::MessageLoop::current()) {
164 base::MessageLoop::current()->PostDelayedTask(
165 FROM_HERE, base::Bind(&RecordSqliteMemory10Min),
166 base::TimeDelta::FromMinutes(10));
167 base::MessageLoop::current()->PostDelayedTask(
168 FROM_HERE, base::Bind(&RecordSqliteMemoryHour),
169 base::TimeDelta::FromHours(1));
170 base::MessageLoop::current()->PostDelayedTask(
171 FROM_HERE, base::Bind(&RecordSqliteMemoryDay),
172 base::TimeDelta::FromDays(1));
shess2d48e942015-08-25 17:39:51173 base::MessageLoop::current()->PostDelayedTask(
174 FROM_HERE, base::Bind(&RecordSqliteMemoryWeek),
175 base::TimeDelta::FromDays(7));
shessc9e80ae22015-08-12 21:39:11176 }
177
178 first_call = false;
179 }
[email protected]a7ec1292013-07-22 22:02:18180}
181
[email protected]8ada10f2013-12-21 00:42:34182// Helper to get the sqlite3_file* associated with the "main" database.
183int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
184 *file = NULL;
185 int rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_FILE_POINTER, file);
186 if (rc != SQLITE_OK)
187 return rc;
188
189 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
190 // content_unittests, even though it should not be possible.
191 // http://crbug.com/329982
192 if (!*file || !(*file)->pMethods)
193 return SQLITE_ERROR;
194
195 return rc;
196}
197
shess5dac334f2015-11-05 20:47:42198// Convenience to get the sqlite3_file* and the size for the "main" database.
199int GetSqlite3FileAndSize(sqlite3* db,
200 sqlite3_file** file, sqlite3_int64* db_size) {
201 int rc = GetSqlite3File(db, file);
202 if (rc != SQLITE_OK)
203 return rc;
204
205 return (*file)->pMethods->xFileSize(*file, db_size);
206}
207
shess58b8df82015-06-03 00:19:32208// This should match UMA_HISTOGRAM_MEDIUM_TIMES().
209base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
210 return base::Histogram::FactoryTimeGet(
211 name,
212 base::TimeDelta::FromMilliseconds(10),
213 base::TimeDelta::FromMinutes(3),
214 50,
215 base::HistogramBase::kUmaTargetedHistogramFlag);
216}
217
erg102ceb412015-06-20 01:38:13218std::string AsUTF8ForSQL(const base::FilePath& path) {
219#if defined(OS_WIN)
220 return base::WideToUTF8(path.value());
221#elif defined(OS_POSIX)
222 return path.value();
223#endif
224}
225
[email protected]5b96f3772010-09-28 16:30:57226} // namespace
227
[email protected]e5ffd0e42009-09-11 21:30:56228namespace sql {
229
[email protected]4350e322013-06-18 22:18:10230// static
231Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL;
232
233// static
[email protected]74cdede2013-09-25 05:39:57234bool Connection::ShouldIgnoreSqliteError(int error) {
[email protected]4350e322013-06-18 22:18:10235 if (!current_ignorer_cb_)
236 return false;
237 return current_ignorer_cb_->Run(error);
238}
239
shessf7e988f2015-11-13 00:41:06240// static
241bool Connection::ShouldIgnoreSqliteCompileError(int error) {
242 // Put this first in case tests need to see that the check happened.
243 if (ShouldIgnoreSqliteError(error))
244 return true;
245
246 // Trim extended error codes.
247 int basic_error = error & 0xff;
248
249 // These errors relate more to the runtime context of the system than to
250 // errors with a SQL statement or with the schema, so they aren't generally
251 // interesting to flag. This list is not comprehensive.
252 return basic_error == SQLITE_BUSY ||
253 basic_error == SQLITE_NOTADB ||
254 basic_error == SQLITE_CORRUPT;
255}
256
shessc8cd2a162015-10-22 20:30:46257void Connection::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
258 AssertIOAllowed();
259
260 std::string debug_info;
261 const int error = (extended_error & 0xFF);
262 if (error == SQLITE_CORRUPT) {
263 debug_info = CollectCorruptionInfo();
264 } else {
265 debug_info = CollectErrorInfo(extended_error, stmt);
266 }
267
268 if (!debug_info.empty() && RegisterIntentToUpload()) {
269 char debug_buf[2000];
270 base::strlcpy(debug_buf, debug_info.c_str(), arraysize(debug_buf));
271 base::debug::Alias(&debug_buf);
272
273 base::debug::DumpWithoutCrashing();
274 }
275}
276
[email protected]4350e322013-06-18 22:18:10277// static
278void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
279 CHECK(current_ignorer_cb_ == NULL);
280 current_ignorer_cb_ = cb;
281}
282
283// static
284void Connection::ResetErrorIgnorer() {
285 CHECK(current_ignorer_cb_);
286 current_ignorer_cb_ = NULL;
287}
288
[email protected]e5ffd0e42009-09-11 21:30:56289bool StatementID::operator<(const StatementID& other) const {
290 if (number_ != other.number_)
291 return number_ < other.number_;
292 return strcmp(str_, other.str_) < 0;
293}
294
[email protected]e5ffd0e42009-09-11 21:30:56295Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38296 sqlite3_stmt* stmt,
297 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56298 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38299 stmt_(stmt),
300 was_valid_(was_valid) {
301 if (connection)
302 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56303}
304
305Connection::StatementRef::~StatementRef() {
306 if (connection_)
307 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38308 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56309}
310
[email protected]41a97c812013-02-07 02:35:38311void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56312 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50313 // Call to AssertIOAllowed() cannot go at the beginning of the function
314 // because Close() is called unconditionally from destructor to clean
315 // connection_. And if this is inactive statement this won't cause any
316 // disk access and destructor most probably will be called on thread
317 // not allowing disk access.
318 // TODO([email protected]): This should move to the beginning
319 // of the function. http://crbug.com/136655.
320 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56321 sqlite3_finalize(stmt_);
322 stmt_ = NULL;
323 }
324 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38325
326 // Forced close is expected to happen from a statement error
327 // handler. In that case maintain the sense of |was_valid_| which
328 // previously held for this ref.
329 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56330}
331
332Connection::Connection()
333 : db_(NULL),
334 page_size_(0),
335 cache_size_(0),
336 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36337 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56338 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50339 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16340 in_memory_(false),
shess58b8df82015-06-03 00:19:32341 poisoned_(false),
shess7dbd4dee2015-10-06 17:39:16342 mmap_disabled_(false),
343 mmap_enabled_(false),
344 total_changes_at_last_release_(0),
shess58b8df82015-06-03 00:19:32345 stats_histogram_(NULL),
346 commit_time_histogram_(NULL),
347 autocommit_time_histogram_(NULL),
348 update_time_histogram_(NULL),
349 query_time_histogram_(NULL),
350 clock_(new TimeSource()) {
[email protected]526b4662013-06-14 04:09:12351}
[email protected]e5ffd0e42009-09-11 21:30:56352
353Connection::~Connection() {
354 Close();
355}
356
shess58b8df82015-06-03 00:19:32357void Connection::RecordEvent(Events event, size_t count) {
358 for (size_t i = 0; i < count; ++i) {
359 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
360 }
361
362 if (stats_histogram_) {
363 for (size_t i = 0; i < count; ++i) {
364 stats_histogram_->Add(event);
365 }
366 }
367}
368
369void Connection::RecordCommitTime(const base::TimeDelta& delta) {
370 RecordUpdateTime(delta);
371 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
372 if (commit_time_histogram_)
373 commit_time_histogram_->AddTime(delta);
374}
375
376void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
377 RecordUpdateTime(delta);
378 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
379 if (autocommit_time_histogram_)
380 autocommit_time_histogram_->AddTime(delta);
381}
382
383void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
384 RecordQueryTime(delta);
385 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
386 if (update_time_histogram_)
387 update_time_histogram_->AddTime(delta);
388}
389
390void Connection::RecordQueryTime(const base::TimeDelta& delta) {
391 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
392 if (query_time_histogram_)
393 query_time_histogram_->AddTime(delta);
394}
395
396void Connection::RecordTimeAndChanges(
397 const base::TimeDelta& delta, bool read_only) {
398 if (read_only) {
399 RecordQueryTime(delta);
400 } else {
401 const int changes = sqlite3_changes(db_);
402 if (sqlite3_get_autocommit(db_)) {
403 RecordAutoCommitTime(delta);
404 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
405 } else {
406 RecordUpdateTime(delta);
407 RecordEvent(EVENT_CHANGES, changes);
408 }
409 }
410}
411
[email protected]a3ef4832013-02-02 05:12:33412bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02413 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26414 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49415 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02416 size_t sample = static_cast<size_t>(size_64 / 1024);
417 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
418 base::HistogramBase* histogram =
419 base::Histogram::FactoryGet(
420 full_histogram_name, 1, 1000000, 50,
421 base::HistogramBase::kUmaTargetedHistogramFlag);
422 if (histogram)
423 histogram->Add(sample);
shess9bf2c672015-12-18 01:18:08424 UMA_HISTOGRAM_COUNTS("Sqlite.SizeKB", sample);
[email protected]348ac8f52013-05-21 03:27:02425 }
426 }
427
erg102ceb412015-06-20 01:38:13428 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42429}
[email protected]e5ffd0e42009-09-11 21:30:56430
[email protected]765b44502009-10-02 05:01:42431bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50432 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13433 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56434}
435
[email protected]8d409412013-07-19 18:25:30436bool Connection::OpenTemporary() {
437 return OpenInternal("", NO_RETRY);
438}
439
[email protected]41a97c812013-02-07 02:35:38440void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47441 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
442 // will delete the -journal file. For ChromiumOS or other more
443 // embedded systems, this is probably not appropriate, whereas on
444 // desktop it might make some sense.
445
[email protected]4b350052012-02-24 20:40:48446 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48447
[email protected]41a97c812013-02-07 02:35:38448 // Release cached statements.
449 statement_cache_.clear();
450
451 // With cached statements released, in-use statements will remain.
452 // Closing the database while statements are in use is an API
453 // violation, except for forced close (which happens from within a
454 // statement's error handler).
455 DCHECK(forced || open_statements_.empty());
456
457 // Deactivate any outstanding statements so sqlite3_close() works.
458 for (StatementRefSet::iterator i = open_statements_.begin();
459 i != open_statements_.end(); ++i)
460 (*i)->Close(forced);
461 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48462
[email protected]e5ffd0e42009-09-11 21:30:56463 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50464 // Call to AssertIOAllowed() cannot go at the beginning of the function
465 // because Close() must be called from destructor to clean
466 // statement_cache_, it won't cause any disk access and it most probably
467 // will happen on thread not allowing disk access.
468 // TODO([email protected]): This should move to the beginning
469 // of the function. http://crbug.com/136655.
470 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28471
ssid3be5b1ec2016-01-13 14:21:57472 // Reseting acquires a lock to ensure no dump is happening on the database
473 // at the same time. Unregister takes ownership of provider and it is safe
474 // since the db is reset. memory_dump_provider_ could be null if db_ was
475 // poisoned.
476 if (memory_dump_provider_) {
477 memory_dump_provider_->ResetDatabase();
478 base::trace_event::MemoryDumpManager::GetInstance()
479 ->UnregisterAndDeleteDumpProviderSoon(
480 std::move(memory_dump_provider_));
481 }
482
[email protected]73fb8d52013-07-24 05:04:28483 int rc = sqlite3_close(db_);
484 if (rc != SQLITE_OK) {
485 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc);
486 DLOG(FATAL) << "sqlite3_close failed: " << GetErrorMessage();
487 }
[email protected]e5ffd0e42009-09-11 21:30:56488 }
[email protected]fed734a2013-07-17 04:45:13489 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56490}
491
[email protected]41a97c812013-02-07 02:35:38492void Connection::Close() {
493 // If the database was already closed by RazeAndClose(), then no
494 // need to close again. Clear the |poisoned_| bit so that incorrect
495 // API calls are caught.
496 if (poisoned_) {
497 poisoned_ = false;
498 return;
499 }
500
501 CloseInternal(false);
502}
503
[email protected]e5ffd0e42009-09-11 21:30:56504void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50505 AssertIOAllowed();
506
[email protected]e5ffd0e42009-09-11 21:30:56507 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38508 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56509 return;
510 }
511
[email protected]8ada10f2013-12-21 00:42:34512 // Use local settings if provided, otherwise use documented defaults. The
513 // actual results could be fetching via PRAGMA calls.
514 const int page_size = page_size_ ? page_size_ : 1024;
515 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
516 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56517 return;
518
[email protected]8ada10f2013-12-21 00:42:34519 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:34520 sqlite3_int64 file_size = 0;
shess5dac334f2015-11-05 20:47:42521 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
[email protected]8ada10f2013-12-21 00:42:34522 if (rc != SQLITE_OK)
523 return;
524
525 // Don't preload more than the file contains.
526 if (preload_size > file_size)
527 preload_size = file_size;
528
529 scoped_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46530 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34531 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
shessd90aeea82015-11-13 02:24:31532
533 // TODO(shess): Consider calling OnSqliteError().
[email protected]8ada10f2013-12-21 00:42:34534 if (rc != SQLITE_OK)
535 return;
536 }
[email protected]e5ffd0e42009-09-11 21:30:56537}
538
shess7dbd4dee2015-10-06 17:39:16539// SQLite keeps unused pages associated with a connection in a cache. It asks
540// the cache for pages by an id, and if the page is present and the database is
541// unchanged, it considers the content of the page valid and doesn't read it
542// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
543// structures created from the memory map data before consulting the cache. On
544// write SQLite creates a new in-memory page structure, copies the data from the
545// memory map, and later writes it, releasing the updated page back to the
546// cache.
547//
548// This means that in memory-mapped mode, the contents of the cached pages are
549// not re-used for reads, but they are re-used for writes if the re-written page
550// is still in the cache. The implementation of sqlite3_db_release_memory() as
551// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
552// connection, so it should free these pages.
553//
554// Unfortunately, the zero page is also freed. That page is never accessed
555// using memory-mapped I/O, and the cached copy can be re-used after verifying
556// the file change counter on disk. Also, fresh pages from cache receive some
557// pager-level initialization before they can be used. Since the information
558// involved will immediately be accessed in various ways, it is unclear if the
559// additional overhead is material, or just moving processor cache effects
560// around.
561//
562// TODO(shess): It would be better to release the pages immediately when they
563// are no longer needed. This would basically happen after SQLite commits a
564// transaction. I had implemented a pcache wrapper to do this, but it involved
565// layering violations, and it had to be setup before any other sqlite call,
566// which was brittle. Also, for large files it would actually make sense to
567// maintain the existing pcache behavior for blocks past the memory-mapped
568// segment. I think drh would accept a reasonable implementation of the overall
569// concept for upstreaming to SQLite core.
570//
571// TODO(shess): Another possibility would be to set the cache size small, which
572// would keep the zero page around, plus some pre-initialized pages, and SQLite
573// can manage things. The downside is that updates larger than the cache would
574// spill to the journal. That could be compensated by setting cache_spill to
575// false. The downside then is that it allows open-ended use of memory for
576// large transactions.
577//
578// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
579// work. There could be two prepared statements, one for cache_size=1 one for
580// cache_size=goal.
581void Connection::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
582 DCHECK(is_open());
583
584 // If memory-mapping is not enabled, the page cache helps performance.
585 if (!mmap_enabled_)
586 return;
587
588 // On caller request, force the change comparison to fail. Done before the
589 // transaction-nesting test so that the signal can carry to transaction
590 // commit.
591 if (implicit_change_performed)
592 --total_changes_at_last_release_;
593
594 // Cached pages may be re-used within the same transaction.
595 if (transaction_nesting())
596 return;
597
598 // If no changes have been made, skip flushing. This allows the first page of
599 // the database to remain in cache across multiple reads.
600 const int total_changes = sqlite3_total_changes(db_);
601 if (total_changes == total_changes_at_last_release_)
602 return;
603
604 total_changes_at_last_release_ = total_changes;
605 sqlite3_db_release_memory(db_);
606}
607
shessc8cd2a162015-10-22 20:30:46608base::FilePath Connection::DbPath() const {
609 if (!is_open())
610 return base::FilePath();
611
612 const char* path = sqlite3_db_filename(db_, "main");
613 const base::StringPiece db_path(path);
614#if defined(OS_WIN)
615 return base::FilePath(base::UTF8ToWide(db_path));
616#elif defined(OS_POSIX)
617 return base::FilePath(db_path);
618#else
619 NOTREACHED();
620 return base::FilePath();
621#endif
622}
623
624// Data is persisted in a file shared between databases in the same directory.
625// The "sqlite-diag" file contains a dictionary with the version number, and an
626// array of histogram tags for databases which have been dumped.
627bool Connection::RegisterIntentToUpload() const {
628 static const char* kVersionKey = "version";
629 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
630 static int kVersion = 1;
631
632 AssertIOAllowed();
633
634 if (histogram_tag_.empty())
635 return false;
636
637 if (!is_open())
638 return false;
639
640 if (in_memory_)
641 return false;
642
643 const base::FilePath db_path = DbPath();
644 if (db_path.empty())
645 return false;
646
647 // Put the collection of diagnostic data next to the databases. In most
648 // cases, this is the profile directory, but safe-browsing stores a Cookies
649 // file in the directory above the profile directory.
650 base::FilePath breadcrumb_path(
651 db_path.DirName().Append(FILE_PATH_LITERAL("sqlite-diag")));
652
653 // Lock against multiple updates to the diagnostics file. This code should
654 // seldom be called in the first place, and when called it should seldom be
655 // called for multiple databases, and when called for multiple databases there
656 // is _probably_ something systemic wrong with the user's system. So the lock
657 // should never be contended, but when it is the database experience is
658 // already bad.
659 base::AutoLock lock(g_sqlite_init_lock.Get());
660
661 scoped_ptr<base::Value> root;
662 if (!base::PathExists(breadcrumb_path)) {
663 scoped_ptr<base::DictionaryValue> root_dict(new base::DictionaryValue());
664 root_dict->SetInteger(kVersionKey, kVersion);
665
666 scoped_ptr<base::ListValue> dumps(new base::ListValue);
667 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50668 root_dict->Set(kDiagnosticDumpsKey, std::move(dumps));
shessc8cd2a162015-10-22 20:30:46669
dchenge48600452015-12-28 02:24:50670 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46671 } else {
672 // Failure to read a valid dictionary implies that something is going wrong
673 // on the system.
674 JSONFileValueDeserializer deserializer(breadcrumb_path);
675 scoped_ptr<base::Value> read_root(
676 deserializer.Deserialize(nullptr, nullptr));
677 if (!read_root.get())
678 return false;
679 scoped_ptr<base::DictionaryValue> root_dict =
dchenge48600452015-12-28 02:24:50680 base::DictionaryValue::From(std::move(read_root));
shessc8cd2a162015-10-22 20:30:46681 if (!root_dict)
682 return false;
683
684 // Don't upload if the version is missing or newer.
685 int version = 0;
686 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
687 return false;
688
689 base::ListValue* dumps = nullptr;
690 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
691 return false;
692
693 const size_t size = dumps->GetSize();
694 for (size_t i = 0; i < size; ++i) {
695 std::string s;
696
697 // Don't upload if the value isn't a string, or indicates a prior upload.
698 if (!dumps->GetString(i, &s) || s == histogram_tag_)
699 return false;
700 }
701
702 // Record intention to proceed with upload.
703 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50704 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46705 }
706
707 const base::FilePath breadcrumb_new =
708 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
709 base::DeleteFile(breadcrumb_new, false);
710
711 // No upload if the breadcrumb file cannot be updated.
712 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
713 // the data on disk. For now, losing the data is not a big problem, so the
714 // sync overhead would probably not be worth it.
715 JSONFileValueSerializer serializer(breadcrumb_new);
716 if (!serializer.Serialize(*root))
717 return false;
718 if (!base::PathExists(breadcrumb_new))
719 return false;
720 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
721 base::DeleteFile(breadcrumb_new, false);
722 return false;
723 }
724
725 return true;
726}
727
728std::string Connection::CollectErrorInfo(int error, Statement* stmt) const {
729 // Buffer for accumulating debugging info about the error. Place
730 // more-relevant information earlier, in case things overflow the
731 // fixed-size reporting buffer.
732 std::string debug_info;
733
734 // The error message from the failed operation.
735 base::StringAppendF(&debug_info, "db error: %d/%s\n",
736 GetErrorCode(), GetErrorMessage());
737
738 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
739 // reading code does not entirely convince me. Remove if they turn out to be
740 // the same.
741 if (error != GetErrorCode())
742 base::StringAppendF(&debug_info, "reported error: %d\n", error);
743
744 // System error information. Interpretation of Windows errors is different
745 // from posix.
746#if defined(OS_WIN)
747 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
748#elif defined(OS_POSIX)
749 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
750#else
751 NOTREACHED(); // Add appropriate log info.
752#endif
753
754 if (stmt) {
755 base::StringAppendF(&debug_info, "statement: %s\n",
756 stmt->GetSQLStatement());
757 } else {
758 base::StringAppendF(&debug_info, "statement: NULL\n");
759 }
760
761 // SQLITE_ERROR often indicates some sort of mismatch between the statement
762 // and the schema, possibly due to a failed schema migration.
763 if (error == SQLITE_ERROR) {
764 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
765 sqlite3_stmt* s;
766 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
767 if (rc == SQLITE_OK) {
768 rc = sqlite3_step(s);
769 if (rc == SQLITE_ROW) {
770 base::StringAppendF(&debug_info, "version: %d\n",
771 sqlite3_column_int(s, 0));
772 } else if (rc == SQLITE_DONE) {
773 debug_info += "version: none\n";
774 } else {
775 base::StringAppendF(&debug_info, "version: error %d\n", rc);
776 }
777 sqlite3_finalize(s);
778 } else {
779 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
780 }
781
782 debug_info += "schema:\n";
783
784 // sqlite_master has columns:
785 // type - "index" or "table".
786 // name - name of created element.
787 // tbl_name - name of element, or target table in case of index.
788 // rootpage - root page of the element in database file.
789 // sql - SQL to create the element.
790 // In general, the |sql| column is sufficient to derive the other columns.
791 // |rootpage| is not interesting for debugging, without the contents of the
792 // database. The COALESCE is because certain automatic elements will have a
793 // |name| but no |sql|,
794 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
795 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
796 if (rc == SQLITE_OK) {
797 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
798 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
799 }
800 if (rc != SQLITE_DONE)
801 base::StringAppendF(&debug_info, "error %d\n", rc);
802 sqlite3_finalize(s);
803 } else {
804 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
805 }
806 }
807
808 return debug_info;
809}
810
811// TODO(shess): Since this is only called in an error situation, it might be
812// prudent to rewrite in terms of SQLite API calls, and mark the function const.
813std::string Connection::CollectCorruptionInfo() {
814 AssertIOAllowed();
815
816 // If the file cannot be accessed it is unlikely that an integrity check will
817 // turn up actionable information.
818 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19819 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46820 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
821 return std::string();
822
823 // Buffer for accumulating debugging info about the error. Place
824 // more-relevant information earlier, in case things overflow the
825 // fixed-size reporting buffer.
826 std::string debug_info;
827 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
828 db_size);
829
830 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19831 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46832 if (db_size > kMaxIntegrityCheckSize) {
833 debug_info += "integrity_check skipped due to size\n";
834 } else {
835 std::vector<std::string> messages;
836
837 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
838 // into a string. Probably should be refactored.
839 const base::TimeTicks before = base::TimeTicks::Now();
840 FullIntegrityCheck(&messages);
841 base::StringAppendF(
842 &debug_info,
843 "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
844 (base::TimeTicks::Now() - before).InMilliseconds(),
845 messages.size());
846
847 // SQLite returns up to 100 messages by default, trim deeper to
848 // keep close to the 2000-character size limit for dumping.
849 const size_t kMaxMessages = 20;
850 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
851 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
852 }
853 }
854
855 return debug_info;
856}
857
shessd90aeea82015-11-13 02:24:31858size_t Connection::GetAppropriateMmapSize() {
859 AssertIOAllowed();
860
shessd90aeea82015-11-13 02:24:31861#if defined(OS_IOS)
862 // iOS SQLite does not support memory mapping.
863 return 0;
864#endif
865
shess9bf2c672015-12-18 01:18:08866 // How much to map if no errors are found. 50MB encompasses the 99th
867 // percentile of Chrome databases in the wild, so this should be good.
868 const size_t kMmapEverything = 256 * 1024 * 1024;
869
870 // If the database doesn't have a place to track progress, assume the best.
871 // This will happen when new databases are created, or if a database doesn't
872 // use a meta table. sql::MetaTable::Init() will preload kMmapSuccess.
873 // TODO(shess): Databases not using meta include:
874 // DOMStorageDatabase (localstorage)
875 // ActivityDatabase (extensions activity log)
876 // PredictorDatabase (prefetch and autocomplete predictor data)
877 // SyncDirectory (sync metadata storage)
878 // For now, these all have mmap disabled to allow other databases to get the
879 // default-enable path. sqlite-diag could be an alternative for all but
880 // DOMStorageDatabase, which creates many small databases.
881 // http://crbug.com/537742
882 if (!MetaTable::DoesTableExist(this)) {
shessd90aeea82015-11-13 02:24:31883 RecordOneEvent(EVENT_MMAP_META_MISSING);
shess9bf2c672015-12-18 01:18:08884 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31885 }
886
shess9bf2c672015-12-18 01:18:08887 int64_t mmap_ofs = 0;
888 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
889 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
890 return 0;
shessd90aeea82015-11-13 02:24:31891 }
892
893 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08894 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31895 RecordOneEvent(EVENT_MMAP_FAILED);
896 return 0;
shess9bf2c672015-12-18 01:18:08897 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31898 // Continue reading from previous offset.
899 DCHECK_GE(mmap_ofs, 0);
900
901 // TODO(shess): Could this reading code be shared with Preload()? It would
902 // require locking twice (this code wouldn't be able to access |db_size| so
903 // the helper would have to return amount read).
904
905 // Read more of the database looking for errors. The VFS interface is used
906 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
907 // to limit checking to 20MB per run of Chromium.
908 sqlite3_file* file = NULL;
909 sqlite3_int64 db_size = 0;
910 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
911 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
912 return 0;
913 }
914
915 // Read the data left, or |g_reads_allowed|, whichever is smaller.
916 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
917 // in a single Chromium run.
918 sqlite3_int64 amount = db_size - mmap_ofs;
919 if (amount < 0)
920 amount = 0;
921 if (amount > 0) {
922 base::AutoLock lock(g_sqlite_init_lock.Get());
923 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
924 if (g_reads_allowed < amount)
925 amount = g_reads_allowed;
926 g_reads_allowed -= amount;
927 }
928
929 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
930 // database was truncated after a previous pass.
931 if (amount <= 0 && mmap_ofs < db_size) {
932 DCHECK_EQ(0, amount);
933 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
934 } else {
935 static const int kPageSize = 4096;
936 char buf[kPageSize];
937 while (amount > 0) {
938 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
939 if (rc == SQLITE_OK) {
940 mmap_ofs += sizeof(buf);
941 amount -= sizeof(buf);
942 } else if (rc == SQLITE_IOERR_SHORT_READ) {
943 // Reached EOF for a database with page size < |kPageSize|.
944 mmap_ofs = db_size;
945 break;
946 } else {
947 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08948 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31949 break;
950 }
951 }
952
953 // Log these events after update to distinguish meta update failure.
954 Events event;
955 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08956 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31957 event = EVENT_MMAP_SUCCESS_NEW;
958 } else if (mmap_ofs > 0) {
959 event = EVENT_MMAP_SUCCESS_PARTIAL;
960 } else {
shess9bf2c672015-12-18 01:18:08961 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31962 event = EVENT_MMAP_FAILED_NEW;
963 }
964
shess9bf2c672015-12-18 01:18:08965 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
shessd90aeea82015-11-13 02:24:31966 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
967 return 0;
968 }
969
970 RecordOneEvent(event);
971 }
972 }
973
shess9bf2c672015-12-18 01:18:08974 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:31975 return 0;
shess9bf2c672015-12-18 01:18:08976 if (mmap_ofs == MetaTable::kMmapSuccess)
977 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31978 return mmap_ofs;
979}
980
[email protected]be7995f12013-07-18 18:49:14981void Connection::TrimMemory(bool aggressively) {
982 if (!db_)
983 return;
984
985 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
986 int original_cache_size;
987 {
988 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
989 if (!sql_get_original.Step()) {
990 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
991 return;
992 }
993 original_cache_size = sql_get_original.ColumnInt(0);
994 }
995 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
996
997 // Force sqlite to try to reduce page cache usage.
998 const std::string sql_shrink =
999 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
1000 if (!Execute(sql_shrink.c_str()))
1001 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
1002
1003 // Restore cache size.
1004 const std::string sql_restore =
1005 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
1006 if (!Execute(sql_restore.c_str()))
1007 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
1008}
1009
[email protected]8e0c01282012-04-06 19:36:491010// Create an in-memory database with the existing database's page
1011// size, then backup that database over the existing database.
1012bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:501013 AssertIOAllowed();
1014
[email protected]8e0c01282012-04-06 19:36:491015 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381016 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491017 return false;
1018 }
1019
1020 if (transaction_nesting_ > 0) {
1021 DLOG(FATAL) << "Cannot raze within a transaction";
1022 return false;
1023 }
1024
1025 sql::Connection null_db;
1026 if (!null_db.OpenInMemory()) {
1027 DLOG(FATAL) << "Unable to open in-memory database.";
1028 return false;
1029 }
1030
[email protected]6d42f152012-11-10 00:38:241031 if (page_size_) {
1032 // Enforce SQLite restrictions on |page_size_|.
1033 DCHECK(!(page_size_ & (page_size_ - 1)))
1034 << " page_size_ " << page_size_ << " is not a power of two.";
1035 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1036 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041037 const std::string sql =
1038 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:421039 if (!null_db.Execute(sql.c_str()))
1040 return false;
1041 }
1042
[email protected]6d42f152012-11-10 00:38:241043#if defined(OS_ANDROID)
1044 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1045 // in-memory databases do not respect this define.
1046 // TODO(shess): Figure out a way to set this without using platform
1047 // specific code. AFAICT from sqlite3.c, the only way to do it
1048 // would be to create an actual filesystem database, which is
1049 // unfortunate.
1050 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1051 return false;
1052#endif
[email protected]8e0c01282012-04-06 19:36:491053
1054 // The page size doesn't take effect until a database has pages, and
1055 // at this point the null database has none. Changing the schema
1056 // version will create the first page. This will not affect the
1057 // schema version in the resulting database, as SQLite's backup
1058 // implementation propagates the schema version from the original
1059 // connection to the new version of the database, incremented by one
1060 // so that other readers see the schema change and act accordingly.
1061 if (!null_db.Execute("PRAGMA schema_version = 1"))
1062 return false;
1063
[email protected]6d42f152012-11-10 00:38:241064 // SQLite tracks the expected number of database pages in the first
1065 // page, and if it does not match the total retrieved from a
1066 // filesystem call, treats the database as corrupt. This situation
1067 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1068 // used to hint to SQLite to soldier on in that case, specifically
1069 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1070 // sqlite3.c lockBtree().]
1071 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1072 // page_size" can be used to query such a database.
1073 ScopedWritableSchema writable_schema(db_);
1074
[email protected]7bae5742013-07-10 20:46:161075 const char* kMain = "main";
1076 int rc = BackupDatabase(null_db.db_, db_, kMain);
1077 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:491078
1079 // The destination database was locked.
1080 if (rc == SQLITE_BUSY) {
1081 return false;
1082 }
1083
[email protected]7bae5742013-07-10 20:46:161084 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1085 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1086 // isn't even big enough for one page. Either way, reach in and
1087 // truncate it before trying again.
1088 // TODO(shess): Maybe it would be worthwhile to just truncate from
1089 // the get-go?
1090 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
1091 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:341092 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161093 if (rc != SQLITE_OK) {
1094 DLOG(FATAL) << "Failure getting file handle.";
1095 return false;
[email protected]7bae5742013-07-10 20:46:161096 }
1097
1098 rc = file->pMethods->xTruncate(file, 0);
1099 if (rc != SQLITE_OK) {
1100 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
1101 DLOG(FATAL) << "Failed to truncate file.";
1102 return false;
1103 }
1104
1105 rc = BackupDatabase(null_db.db_, db_, kMain);
1106 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
1107
1108 if (rc != SQLITE_DONE) {
1109 DLOG(FATAL) << "Failed retrying Raze().";
1110 }
1111 }
1112
[email protected]8e0c01282012-04-06 19:36:491113 // The entire database should have been backed up.
1114 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:161115 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:491116 DLOG(FATAL) << "Unable to copy entire null database.";
1117 return false;
1118 }
1119
[email protected]8e0c01282012-04-06 19:36:491120 return true;
1121}
1122
1123bool Connection::RazeWithTimout(base::TimeDelta timeout) {
1124 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381125 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491126 return false;
1127 }
1128
1129 ScopedBusyTimeout busy_timeout(db_);
1130 busy_timeout.SetTimeout(timeout);
1131 return Raze();
1132}
1133
[email protected]41a97c812013-02-07 02:35:381134bool Connection::RazeAndClose() {
1135 if (!db_) {
1136 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
1137 return false;
1138 }
1139
1140 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301141 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381142
1143 bool result = Raze();
1144
1145 CloseInternal(true);
1146
1147 // Mark the database so that future API calls fail appropriately,
1148 // but don't DCHECK (because after calling this function they are
1149 // expected to fail).
1150 poisoned_ = true;
1151
1152 return result;
1153}
1154
[email protected]8d409412013-07-19 18:25:301155void Connection::Poison() {
1156 if (!db_) {
1157 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
1158 return;
1159 }
1160
1161 RollbackAllTransactions();
1162 CloseInternal(true);
1163
1164 // Mark the database so that future API calls fail appropriately,
1165 // but don't DCHECK (because after calling this function they are
1166 // expected to fail).
1167 poisoned_ = true;
1168}
1169
[email protected]8d2e39e2013-06-24 05:55:081170// TODO(shess): To the extent possible, figure out the optimal
1171// ordering for these deletes which will prevent other connections
1172// from seeing odd behavior. For instance, it may be necessary to
1173// manually lock the main database file in a SQLite-compatible fashion
1174// (to prevent other processes from opening it), then delete the
1175// journal files, then delete the main database file. Another option
1176// might be to lock the main database file and poison the header with
1177// junk to prevent other processes from opening it successfully (like
1178// Gears "SQLite poison 3" trick).
1179//
1180// static
1181bool Connection::Delete(const base::FilePath& path) {
1182 base::ThreadRestrictions::AssertIOAllowed();
1183
1184 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
1185 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
1186
erg102ceb412015-06-20 01:38:131187 std::string journal_str = AsUTF8ForSQL(journal_path);
1188 std::string wal_str = AsUTF8ForSQL(wal_path);
1189 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081190
shess702467622015-09-16 19:04:551191 // Make sure sqlite3_initialize() is called before anything else.
1192 InitializeSqlite();
1193
erg102ceb412015-06-20 01:38:131194 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
1195 CHECK(vfs);
1196 CHECK(vfs->xDelete);
1197 CHECK(vfs->xAccess);
1198
1199 // We only work with unix, win32 and mojo filesystems. If you're trying to
1200 // use this code with any other VFS, you're not in a good place.
1201 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1202 strncmp(vfs->zName, "win32", 5) == 0 ||
1203 strcmp(vfs->zName, "mojo") == 0);
1204
1205 vfs->xDelete(vfs, journal_str.c_str(), 0);
1206 vfs->xDelete(vfs, wal_str.c_str(), 0);
1207 vfs->xDelete(vfs, path_str.c_str(), 0);
1208
1209 int journal_exists = 0;
1210 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
1211 &journal_exists);
1212
1213 int wal_exists = 0;
1214 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
1215 &wal_exists);
1216
1217 int path_exists = 0;
1218 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
1219 &path_exists);
1220
1221 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081222}
1223
[email protected]e5ffd0e42009-09-11 21:30:561224bool Connection::BeginTransaction() {
1225 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331226 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561227
1228 // When we're going to rollback, fail on this begin and don't actually
1229 // mark us as entering the nested transaction.
1230 return false;
1231 }
1232
1233 bool success = true;
1234 if (!transaction_nesting_) {
1235 needs_rollback_ = false;
1236
1237 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321238 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591239 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561240 return false;
1241 }
1242 transaction_nesting_++;
1243 return success;
1244}
1245
1246void Connection::RollbackTransaction() {
1247 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:381248 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561249 return;
1250 }
1251
1252 transaction_nesting_--;
1253
1254 if (transaction_nesting_ > 0) {
1255 // Mark the outermost transaction as needing rollback.
1256 needs_rollback_ = true;
1257 return;
1258 }
1259
1260 DoRollback();
1261}
1262
1263bool Connection::CommitTransaction() {
1264 if (!transaction_nesting_) {
shess90244e12015-11-09 22:08:181265 DLOG_IF(FATAL, !poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561266 return false;
1267 }
1268 transaction_nesting_--;
1269
1270 if (transaction_nesting_ > 0) {
1271 // Mark any nested transactions as failing after we've already got one.
1272 return !needs_rollback_;
1273 }
1274
1275 if (needs_rollback_) {
1276 DoRollback();
1277 return false;
1278 }
1279
1280 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321281
1282 // Collect the commit time manually, sql::Statement would register it as query
1283 // time only.
1284 const base::TimeTicks before = Now();
1285 bool ret = commit.RunWithoutTimers();
1286 const base::TimeDelta delta = Now() - before;
1287
1288 RecordCommitTime(delta);
1289 RecordOneEvent(EVENT_COMMIT);
1290
shess7dbd4dee2015-10-06 17:39:161291 // Release dirty cache pages after the transaction closes.
1292 ReleaseCacheMemoryIfNeeded(false);
1293
shess58b8df82015-06-03 00:19:321294 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561295}
1296
[email protected]8d409412013-07-19 18:25:301297void Connection::RollbackAllTransactions() {
1298 if (transaction_nesting_ > 0) {
1299 transaction_nesting_ = 0;
1300 DoRollback();
1301 }
1302}
1303
1304bool Connection::AttachDatabase(const base::FilePath& other_db_path,
1305 const char* attachment_point) {
1306 DCHECK(ValidAttachmentPoint(attachment_point));
1307
1308 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1309#if OS_WIN
1310 s.BindString16(0, other_db_path.value());
1311#else
1312 s.BindString(0, other_db_path.value());
1313#endif
1314 s.BindString(1, attachment_point);
1315 return s.Run();
1316}
1317
1318bool Connection::DetachDatabase(const char* attachment_point) {
1319 DCHECK(ValidAttachmentPoint(attachment_point));
1320
1321 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1322 s.BindString(0, attachment_point);
1323 return s.Run();
1324}
1325
shess58b8df82015-06-03 00:19:321326// TODO(shess): Consider changing this to execute exactly one statement. If a
1327// caller wishes to execute multiple statements, that should be explicit, and
1328// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591329int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501330 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381331 if (!db_) {
1332 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1333 return SQLITE_ERROR;
1334 }
shess58b8df82015-06-03 00:19:321335 DCHECK(sql);
1336
1337 RecordOneEvent(EVENT_EXECUTE);
1338 int rc = SQLITE_OK;
1339 while ((rc == SQLITE_OK) && *sql) {
1340 sqlite3_stmt *stmt = NULL;
1341 const char *leftover_sql;
1342
1343 const base::TimeTicks before = Now();
1344 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1345 sql = leftover_sql;
1346
1347 // Stop if an error is encountered.
1348 if (rc != SQLITE_OK)
1349 break;
1350
1351 // This happens if |sql| originally only contained comments or whitespace.
1352 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1353 // extraneous comments and whitespace in the SQL statements increases
1354 // runtime cost and can easily be shifted out to the C++ layer.
1355 if (!stmt)
1356 continue;
1357
1358 // Save for use after statement is finalized.
1359 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1360
1361 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1362 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1363 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1364 // is the only legitimate case for this.
1365 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1366 }
1367
1368 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1369 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1370 rc = sqlite3_finalize(stmt);
1371 if (rc == SQLITE_OK)
1372 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1373
1374 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1375 // trailing whitespace.
1376 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021377 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321378 sql++;
1379 }
1380
1381 const base::TimeDelta delta = Now() - before;
1382 RecordTimeAndChanges(delta, read_only);
1383 }
shess7dbd4dee2015-10-06 17:39:161384
1385 // Most calls to Execute() modify the database. The main exceptions would be
1386 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1387 // but sometimes don't.
1388 ReleaseCacheMemoryIfNeeded(true);
1389
shess58b8df82015-06-03 00:19:321390 return rc;
[email protected]eff1fa522011-12-12 23:50:591391}
1392
1393bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381394 if (!db_) {
1395 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1396 return false;
1397 }
1398
[email protected]eff1fa522011-12-12 23:50:591399 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001400 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581401 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001402
[email protected]28fe0ff2012-02-25 00:40:331403 // This needs to be a FATAL log because the error case of arriving here is
1404 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101405 // a change alters the schema but not all queries adjust. This can happen
1406 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:591407 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:331408 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591409 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561410}
1411
[email protected]5b96f3772010-09-28 16:30:571412bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381413 if (!db_) {
1414 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571415 return false;
[email protected]41a97c812013-02-07 02:35:381416 }
[email protected]5b96f3772010-09-28 16:30:571417
1418 ScopedBusyTimeout busy_timeout(db_);
1419 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591420 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571421}
1422
[email protected]e5ffd0e42009-09-11 21:30:561423bool Connection::HasCachedStatement(const StatementID& id) const {
1424 return statement_cache_.find(id) != statement_cache_.end();
1425}
1426
1427scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1428 const StatementID& id,
1429 const char* sql) {
1430 CachedStatementMap::iterator i = statement_cache_.find(id);
1431 if (i != statement_cache_.end()) {
1432 // Statement is in the cache. It should still be active (we're the only
1433 // one invalidating cached statements, and we'll remove it from the cache
1434 // if we do that. Make sure we reset it before giving out the cached one in
1435 // case it still has some stuff bound.
1436 DCHECK(i->second->is_valid());
1437 sqlite3_reset(i->second->stmt());
1438 return i->second;
1439 }
1440
1441 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1442 if (statement->is_valid())
1443 statement_cache_[id] = statement; // Only cache valid statements.
1444 return statement;
1445}
1446
1447scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1448 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501449 AssertIOAllowed();
1450
[email protected]41a97c812013-02-07 02:35:381451 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561452 if (!db_)
[email protected]41a97c812013-02-07 02:35:381453 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561454
1455 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001456 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1457 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591458 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061459 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021460 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001461
1462 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581463 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381464 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561465 }
[email protected]41a97c812013-02-07 02:35:381466 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561467}
1468
shessf7e988f2015-11-13 00:41:061469// TODO(shess): Unify this with GetUniqueStatement(). The only difference that
1470// seems legitimate is not passing |this| to StatementRef.
[email protected]2eec0a22012-07-24 01:59:581471scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1472 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:381473 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:581474 if (!db_)
[email protected]41a97c812013-02-07 02:35:381475 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:581476
1477 sqlite3_stmt* stmt = NULL;
1478 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1479 if (rc != SQLITE_OK) {
1480 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061481 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021482 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:381483 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:581484 }
[email protected]41a97c812013-02-07 02:35:381485 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:581486}
1487
[email protected]92cd00a2013-08-16 11:09:581488std::string Connection::GetSchema() const {
1489 // The ORDER BY should not be necessary, but relying on organic
1490 // order for something like this is questionable.
1491 const char* kSql =
1492 "SELECT type, name, tbl_name, sql "
1493 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1494 Statement statement(GetUntrackedStatement(kSql));
1495
1496 std::string schema;
1497 while (statement.Step()) {
1498 schema += statement.ColumnString(0);
1499 schema += '|';
1500 schema += statement.ColumnString(1);
1501 schema += '|';
1502 schema += statement.ColumnString(2);
1503 schema += '|';
1504 schema += statement.ColumnString(3);
1505 schema += '\n';
1506 }
1507
1508 return schema;
1509}
1510
[email protected]eff1fa522011-12-12 23:50:591511bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501512 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381513 if (!db_) {
1514 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1515 return false;
1516 }
1517
[email protected]eff1fa522011-12-12 23:50:591518 sqlite3_stmt* stmt = NULL;
1519 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1520 return false;
1521
1522 sqlite3_finalize(stmt);
1523 return true;
1524}
1525
[email protected]1ed78a32009-09-15 20:24:171526bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:531527 return DoesTableOrIndexExist(table_name, "table");
1528}
1529
1530bool Connection::DoesIndexExist(const char* index_name) const {
1531 return DoesTableOrIndexExist(index_name, "index");
1532}
1533
1534bool Connection::DoesTableOrIndexExist(
1535 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471536 const char* kSql =
1537 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581538 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471539
1540 // This can happen if the database is corrupt and the error is being ignored
1541 // for testing purposes.
1542 if (!statement.is_valid())
1543 return false;
1544
[email protected]e2cadec82011-12-13 02:00:531545 statement.BindString(0, type);
1546 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331547
[email protected]e5ffd0e42009-09-11 21:30:561548 return statement.Step(); // Table exists if any row was returned.
1549}
1550
1551bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171552 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561553 std::string sql("PRAGMA TABLE_INFO(");
1554 sql.append(table_name);
1555 sql.append(")");
1556
[email protected]2eec0a22012-07-24 01:59:581557 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471558
1559 // This can happen if the database is corrupt and the error is being ignored
1560 // for testing purposes.
1561 if (!statement.is_valid())
1562 return false;
1563
[email protected]e5ffd0e42009-09-11 21:30:561564 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331565 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1566 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561567 return true;
1568 }
1569 return false;
1570}
1571
tfarina720d4f32015-05-11 22:31:261572int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561573 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381574 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561575 return 0;
1576 }
1577 return sqlite3_last_insert_rowid(db_);
1578}
1579
[email protected]1ed78a32009-09-15 20:24:171580int Connection::GetLastChangeCount() const {
1581 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381582 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171583 return 0;
1584 }
1585 return sqlite3_changes(db_);
1586}
1587
[email protected]e5ffd0e42009-09-11 21:30:561588int Connection::GetErrorCode() const {
1589 if (!db_)
1590 return SQLITE_ERROR;
1591 return sqlite3_errcode(db_);
1592}
1593
[email protected]767718e52010-09-21 23:18:491594int Connection::GetLastErrno() const {
1595 if (!db_)
1596 return -1;
1597
1598 int err = 0;
1599 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1600 return -2;
1601
1602 return err;
1603}
1604
[email protected]e5ffd0e42009-09-11 21:30:561605const char* Connection::GetErrorMessage() const {
1606 if (!db_)
1607 return "sql::Connection has no connection.";
1608 return sqlite3_errmsg(db_);
1609}
1610
[email protected]fed734a2013-07-17 04:45:131611bool Connection::OpenInternal(const std::string& file_name,
1612 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501613 AssertIOAllowed();
1614
[email protected]9cfbc922009-11-17 20:13:171615 if (db_) {
[email protected]eff1fa522011-12-12 23:50:591616 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171617 return false;
1618 }
1619
[email protected]a7ec1292013-07-22 22:02:181620 // Make sure sqlite3_initialize() is called before anything else.
1621 InitializeSqlite();
1622
shess58b8df82015-06-03 00:19:321623 // Setup the stats histograms immediately rather than allocating lazily.
1624 // Connections which won't exercise all of these probably shouldn't exist.
1625 if (!histogram_tag_.empty()) {
1626 stats_histogram_ =
1627 base::LinearHistogram::FactoryGet(
1628 "Sqlite.Stats." + histogram_tag_,
1629 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1630 base::HistogramBase::kUmaTargetedHistogramFlag);
1631
1632 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1633 // unreasonable time for any single operation, so there is not much value to
1634 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1635 // things are entirely busted.
1636 commit_time_histogram_ =
1637 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1638
1639 autocommit_time_histogram_ =
1640 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1641
1642 update_time_histogram_ =
1643 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1644
1645 query_time_histogram_ =
1646 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1647 }
1648
[email protected]41a97c812013-02-07 02:35:381649 // If |poisoned_| is set, it means an error handler called
1650 // RazeAndClose(). Until regular Close() is called, the caller
1651 // should be treating the database as open, but is_open() currently
1652 // only considers the sqlite3 handle's state.
1653 // TODO(shess): Revise is_open() to consider poisoned_, and review
1654 // to see if any non-testing code even depends on it.
1655 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161656 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381657
[email protected]765b44502009-10-02 05:01:421658 int err = sqlite3_open(file_name.c_str(), &db_);
1659 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281660 // Extended error codes cannot be enabled until a handle is
1661 // available, fetch manually.
1662 err = sqlite3_extended_errcode(db_);
1663
[email protected]bd2ccdb4a2012-12-07 22:14:501664 // Histogram failures specific to initial open for debugging
1665 // purposes.
[email protected]73fb8d52013-07-24 05:04:281666 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501667
[email protected]2f496b42013-09-26 18:36:581668 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131669 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291670 Close();
[email protected]fed734a2013-07-17 04:45:131671
1672 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1673 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421674 return false;
1675 }
1676
[email protected]81a2a602013-07-17 19:10:361677 // TODO(shess): OS_WIN support?
1678#if defined(OS_POSIX)
1679 if (restrict_to_user_) {
1680 DCHECK_NE(file_name, std::string(":memory"));
1681 base::FilePath file_path(file_name);
1682 int mode = 0;
1683 // TODO(shess): Arguably, failure to retrieve and change
1684 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081685 if (base::GetPosixFilePermissions(file_path, &mode)) {
1686 mode &= base::FILE_PERMISSION_USER_MASK;
1687 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361688
1689 // SQLite sets the permissions on these files from the main
1690 // database on create. Set them here in case they already exist
1691 // at this point. Failure to set these permissions should not
1692 // be fatal unless the file doesn't exist.
1693 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1694 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081695 base::SetPosixFilePermissions(journal_path, mode);
1696 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361697 }
1698 }
1699#endif // defined(OS_POSIX)
1700
[email protected]affa2da2013-06-06 22:20:341701 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1702 // Chromium already depends on small mallocs being efficient, so we disable
1703 // this to avoid the extra memory overhead.
1704 // This must be called immediatly after opening the database before any SQL
1705 // statements are run.
1706 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1707
[email protected]73fb8d52013-07-24 05:04:281708 // Enable extended result codes to provide more color on I/O errors.
1709 // Not having extended result codes is not a fatal problem, as
1710 // Chromium code does not attempt to handle I/O errors anyhow. The
1711 // current implementation always returns SQLITE_OK, the DCHECK is to
1712 // quickly notify someone if SQLite changes.
1713 err = sqlite3_extended_result_codes(db_, 1);
1714 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1715
[email protected]bd2ccdb4a2012-12-07 22:14:501716 // sqlite3_open() does not actually read the database file (unless a
1717 // hot journal is found). Successfully executing this pragma on an
1718 // existing database requires a valid header on page 1.
1719 // TODO(shess): For now, just probing to see what the lay of the
1720 // land is. If it's mostly SQLITE_NOTADB, then the database should
1721 // be razed.
1722 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1723 if (err != SQLITE_OK)
[email protected]73fb8d52013-07-24 05:04:281724 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err);
[email protected]658f8332010-09-18 04:40:431725
[email protected]2e1cee762013-07-09 14:40:001726#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1727 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1728 // REGEXP support. Add it in dynamically.
1729 err = sqlite3IcuInit(db_);
1730 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1731#endif // OS_IOS && USE_SYSTEM_SQLITE
1732
[email protected]5b96f3772010-09-28 16:30:571733 // If indicated, lock up the database before doing anything else, so
1734 // that the following code doesn't have to deal with locking.
1735 // TODO(shess): This code is brittle. Find the cases where code
1736 // doesn't request |exclusive_locking_| and audit that it does the
1737 // right thing with SQLITE_BUSY, and that it doesn't make
1738 // assumptions about who might change things in the database.
1739 // http://crbug.com/56559
1740 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101741 // TODO(shess): This should probably be a failure. Code which
1742 // requests exclusive locking but doesn't get it is almost certain
1743 // to be ill-tested.
1744 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571745 }
1746
[email protected]4e179ba2012-03-17 16:06:471747 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1748 // DELETE (default) - delete -journal file to commit.
1749 // TRUNCATE - truncate -journal file to commit.
1750 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091751 // TRUNCATE should be faster than DELETE because it won't need directory
1752 // changes for each transaction. PERSIST may break the spirit of using
1753 // secure_delete.
1754 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471755
[email protected]c68ce172011-11-24 22:30:271756 const base::TimeDelta kBusyTimeout =
1757 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1758
[email protected]765b44502009-10-02 05:01:421759 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571760 // Enforce SQLite restrictions on |page_size_|.
1761 DCHECK(!(page_size_ & (page_size_ - 1)))
1762 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241763 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571764 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041765 const std::string sql =
1766 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101767 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421768 }
1769
1770 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041771 const std::string sql =
1772 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101773 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421774 }
1775
[email protected]6e0b1442011-08-09 23:23:581776 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131777 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581778 Close();
[email protected]fed734a2013-07-17 04:45:131779 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1780 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581781 return false;
1782 }
1783
shess5dac334f2015-11-05 20:47:421784 // Set a reasonable chunk size for larger files. This reduces churn from
1785 // remapping memory on size changes. It also reduces filesystem
1786 // fragmentation.
1787 // TODO(shess): It may make sense to have this be hinted by the client.
1788 // Database sizes seem to be bimodal, some clients have consistently small
1789 // databases (<20k) while other clients have a broad distribution of sizes
1790 // (hundreds of kilobytes to many megabytes).
1791 sqlite3_file* file = NULL;
1792 sqlite3_int64 db_size = 0;
1793 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1794 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1795 int chunk_size = 4 * 1024;
1796 if (db_size > 128 * 1024)
1797 chunk_size = 32 * 1024;
1798 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1799 }
1800
shess2f3a814b2015-11-05 18:11:101801 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311802 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1803 // safe range to memory-map based on past regular I/O. This value will be
1804 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1805 // 64-bit platforms.
1806 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1807 std::string mmap_sql =
1808 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1809 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101810
1811 // Determine if memory-mapping has actually been enabled. The Execute() above
1812 // can succeed without changing the amount mapped.
1813 mmap_enabled_ = false;
1814 {
1815 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1816 if (s.Step() && s.ColumnInt64(0) > 0)
1817 mmap_enabled_ = true;
1818 }
1819
ssid3be5b1ec2016-01-13 14:21:571820 DCHECK(!memory_dump_provider_);
1821 memory_dump_provider_.reset(
1822 new ConnectionMemoryDumpProvider(db_, histogram_tag_));
1823 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1824 memory_dump_provider_.get(), "sql::Connection", nullptr);
1825
[email protected]765b44502009-10-02 05:01:421826 return true;
1827}
1828
[email protected]e5ffd0e42009-09-11 21:30:561829void Connection::DoRollback() {
1830 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321831
1832 // Collect the rollback time manually, sql::Statement would register it as
1833 // query time only.
1834 const base::TimeTicks before = Now();
1835 rollback.RunWithoutTimers();
1836 const base::TimeDelta delta = Now() - before;
1837
1838 RecordUpdateTime(delta);
1839 RecordOneEvent(EVENT_ROLLBACK);
1840
shess7dbd4dee2015-10-06 17:39:161841 // The cache may have been accumulating dirty pages for commit. Note that in
1842 // some cases sql::Transaction can fire rollback after a database is closed.
1843 if (is_open())
1844 ReleaseCacheMemoryIfNeeded(false);
1845
[email protected]44ad7d902012-03-23 00:09:051846 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561847}
1848
1849void Connection::StatementRefCreated(StatementRef* ref) {
1850 DCHECK(open_statements_.find(ref) == open_statements_.end());
1851 open_statements_.insert(ref);
1852}
1853
1854void Connection::StatementRefDeleted(StatementRef* ref) {
1855 StatementRefSet::iterator i = open_statements_.find(ref);
1856 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:591857 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561858 else
1859 open_statements_.erase(i);
1860}
1861
shess58b8df82015-06-03 00:19:321862void Connection::set_histogram_tag(const std::string& tag) {
1863 DCHECK(!is_open());
1864 histogram_tag_ = tag;
1865}
1866
[email protected]210ce0af2013-05-15 09:10:391867void Connection::AddTaggedHistogram(const std::string& name,
1868 size_t sample) const {
1869 if (histogram_tag_.empty())
1870 return;
1871
1872 // TODO(shess): The histogram macros create a bit of static storage
1873 // for caching the histogram object. This code shouldn't execute
1874 // often enough for such caching to be crucial. If it becomes an
1875 // issue, the object could be cached alongside histogram_prefix_.
1876 std::string full_histogram_name = name + "." + histogram_tag_;
1877 base::HistogramBase* histogram =
1878 base::SparseHistogram::FactoryGet(
1879 full_histogram_name,
1880 base::HistogramBase::kUmaTargetedHistogramFlag);
1881 if (histogram)
1882 histogram->Add(sample);
1883}
1884
[email protected]2f496b42013-09-26 18:36:581885int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) {
[email protected]210ce0af2013-05-15 09:10:391886 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
1887 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141888
1889 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581890 if (!sql && stmt)
1891 sql = stmt->GetSQLStatement();
1892 if (!sql)
1893 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061894
1895 std::string id = histogram_tag_;
1896 if (id.empty())
1897 id = DbPath().BaseName().AsUTF8Unsafe();
1898 LOG(ERROR) << id << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141899 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581900 << ": " << GetErrorMessage()
1901 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141902
[email protected]c3881b372013-05-17 08:39:461903 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561904 // Fire from a copy of the callback in case of reentry into
1905 // re/set_error_callback().
1906 // TODO(shess): <http://crbug.com/254584>
1907 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461908 return err;
1909 }
1910
[email protected]faa604e2009-09-25 22:38:591911 // The default handling is to assert on debug and to ignore on release.
[email protected]74cdede2013-09-25 05:39:571912 if (!ShouldIgnoreSqliteError(err))
[email protected]4350e322013-06-18 22:18:101913 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591914 return err;
1915}
1916
[email protected]579446c2013-12-16 18:36:521917bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1918 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1919}
1920
1921bool Connection::QuickIntegrityCheck() {
1922 std::vector<std::string> messages;
1923 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1924 return false;
1925 return messages.size() == 1 && messages[0] == "ok";
1926}
1927
[email protected]80abf152013-05-22 12:42:421928// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521929bool Connection::IntegrityCheckHelper(
1930 const char* pragma_sql,
1931 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421932 messages->clear();
1933
[email protected]4658e2a02013-06-06 23:05:001934 // This has the side effect of setting SQLITE_RecoveryMode, which
1935 // allows SQLite to process through certain cases of corruption.
1936 // Failing to set this pragma probably means that the database is
1937 // beyond recovery.
1938 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1939 if (!Execute(kWritableSchema))
1940 return false;
1941
1942 bool ret = false;
1943 {
[email protected]579446c2013-12-16 18:36:521944 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001945
1946 // The pragma appears to return all results (up to 100 by default)
1947 // as a single string. This doesn't appear to be an API contract,
1948 // it could return separate lines, so loop _and_ split.
1949 while (stmt.Step()) {
1950 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181951 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1952 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001953 }
1954 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421955 }
[email protected]4658e2a02013-06-06 23:05:001956
1957 // Best effort to put things back as they were before.
1958 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1959 ignore_result(Execute(kNoWritableSchema));
1960
1961 return ret;
[email protected]80abf152013-05-22 12:42:421962}
1963
shess58b8df82015-06-03 00:19:321964base::TimeTicks TimeSource::Now() {
1965 return base::TimeTicks::Now();
1966}
1967
[email protected]e5ffd0e42009-09-11 21:30:561968} // namespace sql