blob: 61aebbe0c94f8640904875d1a7d86a5627906181 [file] [log] [blame]
[email protected]64021042012-02-10 20:02:291// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]e5ffd0e42009-09-11 21:30:562// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f0a54b22011-07-19 18:40:215#include "sql/connection.h"
[email protected]e5ffd0e42009-09-11 21:30:566
7#include <string.h>
8
shessc9e80ae22015-08-12 21:39:119#include "base/bind.h"
[email protected]57999812013-02-24 05:40:5210#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4411#include "base/files/file_util.h"
[email protected]a7ec1292013-07-22 22:02:1812#include "base/lazy_instance.h"
[email protected]e5ffd0e42009-09-11 21:30:5613#include "base/logging.h"
shessc9e80ae22015-08-12 21:39:1114#include "base/message_loop/message_loop.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5015#include "base/metrics/histogram.h"
[email protected]210ce0af2013-05-15 09:10:3916#include "base/metrics/sparse_histogram.h"
[email protected]80abf152013-05-22 12:42:4217#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1918#include "base/strings/string_util.h"
19#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4520#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1821#include "base/synchronization/lock.h"
ssid9f8022f2015-10-12 17:49:0322#include "base/trace_event/memory_dump_manager.h"
23#include "base/trace_event/process_memory_dump.h"
[email protected]f0a54b22011-07-19 18:40:2124#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0325#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5626
[email protected]2e1cee762013-07-09 14:40:0027#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
28#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
29#endif
30
[email protected]5b96f3772010-09-28 16:30:5731namespace {
32
33// Spin for up to a second waiting for the lock to clear when setting
34// up the database.
35// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2736const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5737
38class ScopedBusyTimeout {
39 public:
40 explicit ScopedBusyTimeout(sqlite3* db)
41 : db_(db) {
42 }
43 ~ScopedBusyTimeout() {
44 sqlite3_busy_timeout(db_, 0);
45 }
46
47 int SetTimeout(base::TimeDelta timeout) {
48 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
49 return sqlite3_busy_timeout(db_,
50 static_cast<int>(timeout.InMilliseconds()));
51 }
52
53 private:
54 sqlite3* db_;
55};
56
[email protected]6d42f152012-11-10 00:38:2457// Helper to "safely" enable writable_schema. No error checking
58// because it is reasonable to just forge ahead in case of an error.
59// If turning it on fails, then most likely nothing will work, whereas
60// if turning it off fails, it only matters if some code attempts to
61// continue working with the database and tries to modify the
62// sqlite_master table (none of our code does this).
63class ScopedWritableSchema {
64 public:
65 explicit ScopedWritableSchema(sqlite3* db)
66 : db_(db) {
67 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
68 }
69 ~ScopedWritableSchema() {
70 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
71 }
72
73 private:
74 sqlite3* db_;
75};
76
[email protected]7bae5742013-07-10 20:46:1677// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
78// SQLite error code from running the backup step.
79int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
80 DCHECK_NE(src, dst);
81 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
82 if (!backup) {
83 // Since this call only sets things up, this indicates a gross
84 // error in SQLite.
85 DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
86 return sqlite3_errcode(dst);
87 }
88
89 // -1 backs up the entire database.
90 int rc = sqlite3_backup_step(backup, -1);
91 int pages = sqlite3_backup_pagecount(backup);
92 sqlite3_backup_finish(backup);
93
94 // If successful, exactly one page should have been backed up. If
95 // this breaks, check this function to make sure assumptions aren't
96 // being broken.
97 if (rc == SQLITE_DONE)
98 DCHECK_EQ(pages, 1);
99
100 return rc;
101}
102
[email protected]8d409412013-07-19 18:25:30103// Be very strict on attachment point. SQLite can handle a much wider
104// character set with appropriate quoting, but Chromium code should
105// just use clean names to start with.
106bool ValidAttachmentPoint(const char* attachment_point) {
107 for (size_t i = 0; attachment_point[i]; ++i) {
108 if (!((attachment_point[i] >= '0' && attachment_point[i] <= '9') ||
109 (attachment_point[i] >= 'a' && attachment_point[i] <= 'z') ||
110 (attachment_point[i] >= 'A' && attachment_point[i] <= 'Z') ||
111 attachment_point[i] == '_')) {
112 return false;
113 }
114 }
115 return true;
116}
117
shessc9e80ae22015-08-12 21:39:11118void RecordSqliteMemory10Min() {
119 const int64 used = sqlite3_memory_used();
120 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.TenMinutes", used / 1024);
121}
122
123void RecordSqliteMemoryHour() {
124 const int64 used = sqlite3_memory_used();
125 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneHour", used / 1024);
126}
127
128void RecordSqliteMemoryDay() {
129 const int64 used = sqlite3_memory_used();
130 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneDay", used / 1024);
131}
132
shess2d48e942015-08-25 17:39:51133void RecordSqliteMemoryWeek() {
134 const int64 used = sqlite3_memory_used();
135 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneWeek", used / 1024);
136}
137
[email protected]a7ec1292013-07-22 22:02:18138// SQLite automatically calls sqlite3_initialize() lazily, but
139// sqlite3_initialize() uses double-checked locking and thus can have
140// data races.
141//
142// TODO(shess): Another alternative would be to have
143// sqlite3_initialize() called as part of process bring-up. If this
144// is changed, remove the dynamic_annotations dependency in sql.gyp.
145base::LazyInstance<base::Lock>::Leaky
146 g_sqlite_init_lock = LAZY_INSTANCE_INITIALIZER;
147void InitializeSqlite() {
148 base::AutoLock lock(g_sqlite_init_lock.Get());
shessc9e80ae22015-08-12 21:39:11149 static bool first_call = true;
150 if (first_call) {
151 sqlite3_initialize();
152
153 // Schedule callback to record memory footprint histograms at 10m, 1h, and
154 // 1d. There may not be a message loop in tests.
155 if (base::MessageLoop::current()) {
156 base::MessageLoop::current()->PostDelayedTask(
157 FROM_HERE, base::Bind(&RecordSqliteMemory10Min),
158 base::TimeDelta::FromMinutes(10));
159 base::MessageLoop::current()->PostDelayedTask(
160 FROM_HERE, base::Bind(&RecordSqliteMemoryHour),
161 base::TimeDelta::FromHours(1));
162 base::MessageLoop::current()->PostDelayedTask(
163 FROM_HERE, base::Bind(&RecordSqliteMemoryDay),
164 base::TimeDelta::FromDays(1));
shess2d48e942015-08-25 17:39:51165 base::MessageLoop::current()->PostDelayedTask(
166 FROM_HERE, base::Bind(&RecordSqliteMemoryWeek),
167 base::TimeDelta::FromDays(7));
shessc9e80ae22015-08-12 21:39:11168 }
169
170 first_call = false;
171 }
[email protected]a7ec1292013-07-22 22:02:18172}
173
[email protected]8ada10f2013-12-21 00:42:34174// Helper to get the sqlite3_file* associated with the "main" database.
175int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
176 *file = NULL;
177 int rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_FILE_POINTER, file);
178 if (rc != SQLITE_OK)
179 return rc;
180
181 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
182 // content_unittests, even though it should not be possible.
183 // http://crbug.com/329982
184 if (!*file || !(*file)->pMethods)
185 return SQLITE_ERROR;
186
187 return rc;
188}
189
shess58b8df82015-06-03 00:19:32190// This should match UMA_HISTOGRAM_MEDIUM_TIMES().
191base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
192 return base::Histogram::FactoryTimeGet(
193 name,
194 base::TimeDelta::FromMilliseconds(10),
195 base::TimeDelta::FromMinutes(3),
196 50,
197 base::HistogramBase::kUmaTargetedHistogramFlag);
198}
199
erg102ceb412015-06-20 01:38:13200std::string AsUTF8ForSQL(const base::FilePath& path) {
201#if defined(OS_WIN)
202 return base::WideToUTF8(path.value());
203#elif defined(OS_POSIX)
204 return path.value();
205#endif
206}
207
[email protected]5b96f3772010-09-28 16:30:57208} // namespace
209
[email protected]e5ffd0e42009-09-11 21:30:56210namespace sql {
211
[email protected]4350e322013-06-18 22:18:10212// static
213Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL;
214
215// static
[email protected]74cdede2013-09-25 05:39:57216bool Connection::ShouldIgnoreSqliteError(int error) {
[email protected]4350e322013-06-18 22:18:10217 if (!current_ignorer_cb_)
218 return false;
219 return current_ignorer_cb_->Run(error);
220}
221
ssid9f8022f2015-10-12 17:49:03222bool Connection::OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
223 base::trace_event::ProcessMemoryDump* pmd) {
224 if (args.level_of_detail ==
225 base::trace_event::MemoryDumpLevelOfDetail::LIGHT ||
226 !db_) {
227 return true;
228 }
229
230 // The high water mark is not tracked for the following usages.
231 int cache_size, dummy_int;
232 sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED, &cache_size, &dummy_int,
233 0 /* resetFlag */);
234 int schema_size;
235 sqlite3_db_status(db_, SQLITE_DBSTATUS_SCHEMA_USED, &schema_size, &dummy_int,
236 0 /* resetFlag */);
237 int statement_size;
238 sqlite3_db_status(db_, SQLITE_DBSTATUS_STMT_USED, &statement_size, &dummy_int,
239 0 /* resetFlag */);
240
241 std::string name = base::StringPrintf(
242 "sqlite/%s_connection/%p",
243 histogram_tag_.empty() ? "Unknown" : histogram_tag_.c_str(), this);
244 base::trace_event::MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(name);
245 dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
246 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
247 cache_size + schema_size + statement_size);
248 dump->AddScalar("cache_size",
249 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
250 cache_size);
251 dump->AddScalar("schema_size",
252 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
253 schema_size);
254 dump->AddScalar("statement_size",
255 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
256 statement_size);
257 return true;
258}
259
[email protected]4350e322013-06-18 22:18:10260// static
261void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
262 CHECK(current_ignorer_cb_ == NULL);
263 current_ignorer_cb_ = cb;
264}
265
266// static
267void Connection::ResetErrorIgnorer() {
268 CHECK(current_ignorer_cb_);
269 current_ignorer_cb_ = NULL;
270}
271
[email protected]e5ffd0e42009-09-11 21:30:56272bool StatementID::operator<(const StatementID& other) const {
273 if (number_ != other.number_)
274 return number_ < other.number_;
275 return strcmp(str_, other.str_) < 0;
276}
277
[email protected]e5ffd0e42009-09-11 21:30:56278Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38279 sqlite3_stmt* stmt,
280 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56281 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38282 stmt_(stmt),
283 was_valid_(was_valid) {
284 if (connection)
285 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56286}
287
288Connection::StatementRef::~StatementRef() {
289 if (connection_)
290 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38291 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56292}
293
[email protected]41a97c812013-02-07 02:35:38294void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56295 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50296 // Call to AssertIOAllowed() cannot go at the beginning of the function
297 // because Close() is called unconditionally from destructor to clean
298 // connection_. And if this is inactive statement this won't cause any
299 // disk access and destructor most probably will be called on thread
300 // not allowing disk access.
301 // TODO([email protected]): This should move to the beginning
302 // of the function. http://crbug.com/136655.
303 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56304 sqlite3_finalize(stmt_);
305 stmt_ = NULL;
306 }
307 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38308
309 // Forced close is expected to happen from a statement error
310 // handler. In that case maintain the sense of |was_valid_| which
311 // previously held for this ref.
312 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56313}
314
315Connection::Connection()
316 : db_(NULL),
317 page_size_(0),
318 cache_size_(0),
319 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36320 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56321 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50322 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16323 in_memory_(false),
shess58b8df82015-06-03 00:19:32324 poisoned_(false),
shess7dbd4dee2015-10-06 17:39:16325 mmap_disabled_(false),
326 mmap_enabled_(false),
327 total_changes_at_last_release_(0),
shess58b8df82015-06-03 00:19:32328 stats_histogram_(NULL),
329 commit_time_histogram_(NULL),
330 autocommit_time_histogram_(NULL),
331 update_time_histogram_(NULL),
332 query_time_histogram_(NULL),
333 clock_(new TimeSource()) {
ssid9f8022f2015-10-12 17:49:03334 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
335 this);
[email protected]526b4662013-06-14 04:09:12336}
[email protected]e5ffd0e42009-09-11 21:30:56337
338Connection::~Connection() {
ssid9f8022f2015-10-12 17:49:03339 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
340 this);
[email protected]e5ffd0e42009-09-11 21:30:56341 Close();
342}
343
shess58b8df82015-06-03 00:19:32344void Connection::RecordEvent(Events event, size_t count) {
345 for (size_t i = 0; i < count; ++i) {
346 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
347 }
348
349 if (stats_histogram_) {
350 for (size_t i = 0; i < count; ++i) {
351 stats_histogram_->Add(event);
352 }
353 }
354}
355
356void Connection::RecordCommitTime(const base::TimeDelta& delta) {
357 RecordUpdateTime(delta);
358 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
359 if (commit_time_histogram_)
360 commit_time_histogram_->AddTime(delta);
361}
362
363void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
364 RecordUpdateTime(delta);
365 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
366 if (autocommit_time_histogram_)
367 autocommit_time_histogram_->AddTime(delta);
368}
369
370void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
371 RecordQueryTime(delta);
372 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
373 if (update_time_histogram_)
374 update_time_histogram_->AddTime(delta);
375}
376
377void Connection::RecordQueryTime(const base::TimeDelta& delta) {
378 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
379 if (query_time_histogram_)
380 query_time_histogram_->AddTime(delta);
381}
382
383void Connection::RecordTimeAndChanges(
384 const base::TimeDelta& delta, bool read_only) {
385 if (read_only) {
386 RecordQueryTime(delta);
387 } else {
388 const int changes = sqlite3_changes(db_);
389 if (sqlite3_get_autocommit(db_)) {
390 RecordAutoCommitTime(delta);
391 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
392 } else {
393 RecordUpdateTime(delta);
394 RecordEvent(EVENT_CHANGES, changes);
395 }
396 }
397}
398
[email protected]a3ef4832013-02-02 05:12:33399bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02400 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26401 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49402 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02403 size_t sample = static_cast<size_t>(size_64 / 1024);
404 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
405 base::HistogramBase* histogram =
406 base::Histogram::FactoryGet(
407 full_histogram_name, 1, 1000000, 50,
408 base::HistogramBase::kUmaTargetedHistogramFlag);
409 if (histogram)
410 histogram->Add(sample);
411 }
412 }
413
erg102ceb412015-06-20 01:38:13414 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42415}
[email protected]e5ffd0e42009-09-11 21:30:56416
[email protected]765b44502009-10-02 05:01:42417bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50418 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13419 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56420}
421
[email protected]8d409412013-07-19 18:25:30422bool Connection::OpenTemporary() {
423 return OpenInternal("", NO_RETRY);
424}
425
[email protected]41a97c812013-02-07 02:35:38426void Connection::CloseInternal(bool forced) {
[email protected]4e179ba62012-03-17 16:06:47427 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
428 // will delete the -journal file. For ChromiumOS or other more
429 // embedded systems, this is probably not appropriate, whereas on
430 // desktop it might make some sense.
431
[email protected]4b350052012-02-24 20:40:48432 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48433
[email protected]41a97c812013-02-07 02:35:38434 // Release cached statements.
435 statement_cache_.clear();
436
437 // With cached statements released, in-use statements will remain.
438 // Closing the database while statements are in use is an API
439 // violation, except for forced close (which happens from within a
440 // statement's error handler).
441 DCHECK(forced || open_statements_.empty());
442
443 // Deactivate any outstanding statements so sqlite3_close() works.
444 for (StatementRefSet::iterator i = open_statements_.begin();
445 i != open_statements_.end(); ++i)
446 (*i)->Close(forced);
447 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48448
[email protected]e5ffd0e42009-09-11 21:30:56449 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50450 // Call to AssertIOAllowed() cannot go at the beginning of the function
451 // because Close() must be called from destructor to clean
452 // statement_cache_, it won't cause any disk access and it most probably
453 // will happen on thread not allowing disk access.
454 // TODO([email protected]): This should move to the beginning
455 // of the function. http://crbug.com/136655.
456 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28457
458 int rc = sqlite3_close(db_);
459 if (rc != SQLITE_OK) {
460 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc);
461 DLOG(FATAL) << "sqlite3_close failed: " << GetErrorMessage();
462 }
[email protected]e5ffd0e42009-09-11 21:30:56463 }
[email protected]fed734a2013-07-17 04:45:13464 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56465}
466
[email protected]41a97c812013-02-07 02:35:38467void Connection::Close() {
468 // If the database was already closed by RazeAndClose(), then no
469 // need to close again. Clear the |poisoned_| bit so that incorrect
470 // API calls are caught.
471 if (poisoned_) {
472 poisoned_ = false;
473 return;
474 }
475
476 CloseInternal(false);
477}
478
[email protected]e5ffd0e42009-09-11 21:30:56479void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50480 AssertIOAllowed();
481
[email protected]e5ffd0e42009-09-11 21:30:56482 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38483 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56484 return;
485 }
486
[email protected]8ada10f2013-12-21 00:42:34487 // Use local settings if provided, otherwise use documented defaults. The
488 // actual results could be fetching via PRAGMA calls.
489 const int page_size = page_size_ ? page_size_ : 1024;
490 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
491 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56492 return;
493
[email protected]8ada10f2013-12-21 00:42:34494 sqlite3_file* file = NULL;
495 int rc = GetSqlite3File(db_, &file);
496 if (rc != SQLITE_OK)
497 return;
498
499 sqlite3_int64 file_size = 0;
500 rc = file->pMethods->xFileSize(file, &file_size);
501 if (rc != SQLITE_OK)
502 return;
503
504 // Don't preload more than the file contains.
505 if (preload_size > file_size)
506 preload_size = file_size;
507
508 scoped_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46509 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34510 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
511 if (rc != SQLITE_OK)
512 return;
513 }
[email protected]e5ffd0e42009-09-11 21:30:56514}
515
shess7dbd4dee2015-10-06 17:39:16516// SQLite keeps unused pages associated with a connection in a cache. It asks
517// the cache for pages by an id, and if the page is present and the database is
518// unchanged, it considers the content of the page valid and doesn't read it
519// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
520// structures created from the memory map data before consulting the cache. On
521// write SQLite creates a new in-memory page structure, copies the data from the
522// memory map, and later writes it, releasing the updated page back to the
523// cache.
524//
525// This means that in memory-mapped mode, the contents of the cached pages are
526// not re-used for reads, but they are re-used for writes if the re-written page
527// is still in the cache. The implementation of sqlite3_db_release_memory() as
528// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
529// connection, so it should free these pages.
530//
531// Unfortunately, the zero page is also freed. That page is never accessed
532// using memory-mapped I/O, and the cached copy can be re-used after verifying
533// the file change counter on disk. Also, fresh pages from cache receive some
534// pager-level initialization before they can be used. Since the information
535// involved will immediately be accessed in various ways, it is unclear if the
536// additional overhead is material, or just moving processor cache effects
537// around.
538//
539// TODO(shess): It would be better to release the pages immediately when they
540// are no longer needed. This would basically happen after SQLite commits a
541// transaction. I had implemented a pcache wrapper to do this, but it involved
542// layering violations, and it had to be setup before any other sqlite call,
543// which was brittle. Also, for large files it would actually make sense to
544// maintain the existing pcache behavior for blocks past the memory-mapped
545// segment. I think drh would accept a reasonable implementation of the overall
546// concept for upstreaming to SQLite core.
547//
548// TODO(shess): Another possibility would be to set the cache size small, which
549// would keep the zero page around, plus some pre-initialized pages, and SQLite
550// can manage things. The downside is that updates larger than the cache would
551// spill to the journal. That could be compensated by setting cache_spill to
552// false. The downside then is that it allows open-ended use of memory for
553// large transactions.
554//
555// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
556// work. There could be two prepared statements, one for cache_size=1 one for
557// cache_size=goal.
558void Connection::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
559 DCHECK(is_open());
560
561 // If memory-mapping is not enabled, the page cache helps performance.
562 if (!mmap_enabled_)
563 return;
564
565 // On caller request, force the change comparison to fail. Done before the
566 // transaction-nesting test so that the signal can carry to transaction
567 // commit.
568 if (implicit_change_performed)
569 --total_changes_at_last_release_;
570
571 // Cached pages may be re-used within the same transaction.
572 if (transaction_nesting())
573 return;
574
575 // If no changes have been made, skip flushing. This allows the first page of
576 // the database to remain in cache across multiple reads.
577 const int total_changes = sqlite3_total_changes(db_);
578 if (total_changes == total_changes_at_last_release_)
579 return;
580
581 total_changes_at_last_release_ = total_changes;
582 sqlite3_db_release_memory(db_);
583}
584
[email protected]be7995f12013-07-18 18:49:14585void Connection::TrimMemory(bool aggressively) {
586 if (!db_)
587 return;
588
589 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
590 int original_cache_size;
591 {
592 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
593 if (!sql_get_original.Step()) {
594 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
595 return;
596 }
597 original_cache_size = sql_get_original.ColumnInt(0);
598 }
599 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
600
601 // Force sqlite to try to reduce page cache usage.
602 const std::string sql_shrink =
603 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
604 if (!Execute(sql_shrink.c_str()))
605 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
606
607 // Restore cache size.
608 const std::string sql_restore =
609 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
610 if (!Execute(sql_restore.c_str()))
611 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
612}
613
[email protected]8e0c01282012-04-06 19:36:49614// Create an in-memory database with the existing database's page
615// size, then backup that database over the existing database.
616bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50617 AssertIOAllowed();
618
[email protected]8e0c01282012-04-06 19:36:49619 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38620 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49621 return false;
622 }
623
624 if (transaction_nesting_ > 0) {
625 DLOG(FATAL) << "Cannot raze within a transaction";
626 return false;
627 }
628
629 sql::Connection null_db;
630 if (!null_db.OpenInMemory()) {
631 DLOG(FATAL) << "Unable to open in-memory database.";
632 return false;
633 }
634
[email protected]6d42f152012-11-10 00:38:24635 if (page_size_) {
636 // Enforce SQLite restrictions on |page_size_|.
637 DCHECK(!(page_size_ & (page_size_ - 1)))
638 << " page_size_ " << page_size_ << " is not a power of two.";
639 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
640 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04641 const std::string sql =
642 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:42643 if (!null_db.Execute(sql.c_str()))
644 return false;
645 }
646
[email protected]6d42f152012-11-10 00:38:24647#if defined(OS_ANDROID)
648 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
649 // in-memory databases do not respect this define.
650 // TODO(shess): Figure out a way to set this without using platform
651 // specific code. AFAICT from sqlite3.c, the only way to do it
652 // would be to create an actual filesystem database, which is
653 // unfortunate.
654 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
655 return false;
656#endif
[email protected]8e0c01282012-04-06 19:36:49657
658 // The page size doesn't take effect until a database has pages, and
659 // at this point the null database has none. Changing the schema
660 // version will create the first page. This will not affect the
661 // schema version in the resulting database, as SQLite's backup
662 // implementation propagates the schema version from the original
663 // connection to the new version of the database, incremented by one
664 // so that other readers see the schema change and act accordingly.
665 if (!null_db.Execute("PRAGMA schema_version = 1"))
666 return false;
667
[email protected]6d42f152012-11-10 00:38:24668 // SQLite tracks the expected number of database pages in the first
669 // page, and if it does not match the total retrieved from a
670 // filesystem call, treats the database as corrupt. This situation
671 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
672 // used to hint to SQLite to soldier on in that case, specifically
673 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
674 // sqlite3.c lockBtree().]
675 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
676 // page_size" can be used to query such a database.
677 ScopedWritableSchema writable_schema(db_);
678
[email protected]7bae5742013-07-10 20:46:16679 const char* kMain = "main";
680 int rc = BackupDatabase(null_db.db_, db_, kMain);
681 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:49682
683 // The destination database was locked.
684 if (rc == SQLITE_BUSY) {
685 return false;
686 }
687
[email protected]7bae5742013-07-10 20:46:16688 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
689 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
690 // isn't even big enough for one page. Either way, reach in and
691 // truncate it before trying again.
692 // TODO(shess): Maybe it would be worthwhile to just truncate from
693 // the get-go?
694 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
695 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:34696 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:16697 if (rc != SQLITE_OK) {
698 DLOG(FATAL) << "Failure getting file handle.";
699 return false;
[email protected]7bae5742013-07-10 20:46:16700 }
701
702 rc = file->pMethods->xTruncate(file, 0);
703 if (rc != SQLITE_OK) {
704 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
705 DLOG(FATAL) << "Failed to truncate file.";
706 return false;
707 }
708
709 rc = BackupDatabase(null_db.db_, db_, kMain);
710 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
711
712 if (rc != SQLITE_DONE) {
713 DLOG(FATAL) << "Failed retrying Raze().";
714 }
715 }
716
[email protected]8e0c01282012-04-06 19:36:49717 // The entire database should have been backed up.
718 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:16719 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:49720 DLOG(FATAL) << "Unable to copy entire null database.";
721 return false;
722 }
723
[email protected]8e0c01282012-04-06 19:36:49724 return true;
725}
726
727bool Connection::RazeWithTimout(base::TimeDelta timeout) {
728 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38729 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49730 return false;
731 }
732
733 ScopedBusyTimeout busy_timeout(db_);
734 busy_timeout.SetTimeout(timeout);
735 return Raze();
736}
737
[email protected]41a97c812013-02-07 02:35:38738bool Connection::RazeAndClose() {
739 if (!db_) {
740 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
741 return false;
742 }
743
744 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:30745 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:38746
747 bool result = Raze();
748
749 CloseInternal(true);
750
751 // Mark the database so that future API calls fail appropriately,
752 // but don't DCHECK (because after calling this function they are
753 // expected to fail).
754 poisoned_ = true;
755
756 return result;
757}
758
[email protected]8d409412013-07-19 18:25:30759void Connection::Poison() {
760 if (!db_) {
761 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
762 return;
763 }
764
765 RollbackAllTransactions();
766 CloseInternal(true);
767
768 // Mark the database so that future API calls fail appropriately,
769 // but don't DCHECK (because after calling this function they are
770 // expected to fail).
771 poisoned_ = true;
772}
773
[email protected]8d2e39e2013-06-24 05:55:08774// TODO(shess): To the extent possible, figure out the optimal
775// ordering for these deletes which will prevent other connections
776// from seeing odd behavior. For instance, it may be necessary to
777// manually lock the main database file in a SQLite-compatible fashion
778// (to prevent other processes from opening it), then delete the
779// journal files, then delete the main database file. Another option
780// might be to lock the main database file and poison the header with
781// junk to prevent other processes from opening it successfully (like
782// Gears "SQLite poison 3" trick).
783//
784// static
785bool Connection::Delete(const base::FilePath& path) {
786 base::ThreadRestrictions::AssertIOAllowed();
787
788 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
789 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
790
erg102ceb412015-06-20 01:38:13791 std::string journal_str = AsUTF8ForSQL(journal_path);
792 std::string wal_str = AsUTF8ForSQL(wal_path);
793 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:08794
shess702467622015-09-16 19:04:55795 // Make sure sqlite3_initialize() is called before anything else.
796 InitializeSqlite();
797
erg102ceb412015-06-20 01:38:13798 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
799 CHECK(vfs);
800 CHECK(vfs->xDelete);
801 CHECK(vfs->xAccess);
802
803 // We only work with unix, win32 and mojo filesystems. If you're trying to
804 // use this code with any other VFS, you're not in a good place.
805 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
806 strncmp(vfs->zName, "win32", 5) == 0 ||
807 strcmp(vfs->zName, "mojo") == 0);
808
809 vfs->xDelete(vfs, journal_str.c_str(), 0);
810 vfs->xDelete(vfs, wal_str.c_str(), 0);
811 vfs->xDelete(vfs, path_str.c_str(), 0);
812
813 int journal_exists = 0;
814 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
815 &journal_exists);
816
817 int wal_exists = 0;
818 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
819 &wal_exists);
820
821 int path_exists = 0;
822 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
823 &path_exists);
824
825 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:08826}
827
[email protected]e5ffd0e42009-09-11 21:30:56828bool Connection::BeginTransaction() {
829 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33830 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56831
832 // When we're going to rollback, fail on this begin and don't actually
833 // mark us as entering the nested transaction.
834 return false;
835 }
836
837 bool success = true;
838 if (!transaction_nesting_) {
839 needs_rollback_ = false;
840
841 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:32842 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:59843 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56844 return false;
845 }
846 transaction_nesting_++;
847 return success;
848}
849
850void Connection::RollbackTransaction() {
851 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38852 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56853 return;
854 }
855
856 transaction_nesting_--;
857
858 if (transaction_nesting_ > 0) {
859 // Mark the outermost transaction as needing rollback.
860 needs_rollback_ = true;
861 return;
862 }
863
864 DoRollback();
865}
866
867bool Connection::CommitTransaction() {
868 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38869 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56870 return false;
871 }
872 transaction_nesting_--;
873
874 if (transaction_nesting_ > 0) {
875 // Mark any nested transactions as failing after we've already got one.
876 return !needs_rollback_;
877 }
878
879 if (needs_rollback_) {
880 DoRollback();
881 return false;
882 }
883
884 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:32885
886 // Collect the commit time manually, sql::Statement would register it as query
887 // time only.
888 const base::TimeTicks before = Now();
889 bool ret = commit.RunWithoutTimers();
890 const base::TimeDelta delta = Now() - before;
891
892 RecordCommitTime(delta);
893 RecordOneEvent(EVENT_COMMIT);
894
shess7dbd4dee2015-10-06 17:39:16895 // Release dirty cache pages after the transaction closes.
896 ReleaseCacheMemoryIfNeeded(false);
897
shess58b8df82015-06-03 00:19:32898 return ret;
[email protected]e5ffd0e42009-09-11 21:30:56899}
900
[email protected]8d409412013-07-19 18:25:30901void Connection::RollbackAllTransactions() {
902 if (transaction_nesting_ > 0) {
903 transaction_nesting_ = 0;
904 DoRollback();
905 }
906}
907
908bool Connection::AttachDatabase(const base::FilePath& other_db_path,
909 const char* attachment_point) {
910 DCHECK(ValidAttachmentPoint(attachment_point));
911
912 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
913#if OS_WIN
914 s.BindString16(0, other_db_path.value());
915#else
916 s.BindString(0, other_db_path.value());
917#endif
918 s.BindString(1, attachment_point);
919 return s.Run();
920}
921
922bool Connection::DetachDatabase(const char* attachment_point) {
923 DCHECK(ValidAttachmentPoint(attachment_point));
924
925 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
926 s.BindString(0, attachment_point);
927 return s.Run();
928}
929
shess58b8df82015-06-03 00:19:32930// TODO(shess): Consider changing this to execute exactly one statement. If a
931// caller wishes to execute multiple statements, that should be explicit, and
932// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:59933int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50934 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38935 if (!db_) {
936 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
937 return SQLITE_ERROR;
938 }
shess58b8df82015-06-03 00:19:32939 DCHECK(sql);
940
941 RecordOneEvent(EVENT_EXECUTE);
942 int rc = SQLITE_OK;
943 while ((rc == SQLITE_OK) && *sql) {
944 sqlite3_stmt *stmt = NULL;
945 const char *leftover_sql;
946
947 const base::TimeTicks before = Now();
948 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
949 sql = leftover_sql;
950
951 // Stop if an error is encountered.
952 if (rc != SQLITE_OK)
953 break;
954
955 // This happens if |sql| originally only contained comments or whitespace.
956 // TODO(shess): Audit to see if this can become a DCHECK(). Having
957 // extraneous comments and whitespace in the SQL statements increases
958 // runtime cost and can easily be shifted out to the C++ layer.
959 if (!stmt)
960 continue;
961
962 // Save for use after statement is finalized.
963 const bool read_only = !!sqlite3_stmt_readonly(stmt);
964
965 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
966 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
967 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
968 // is the only legitimate case for this.
969 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
970 }
971
972 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
973 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
974 rc = sqlite3_finalize(stmt);
975 if (rc == SQLITE_OK)
976 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
977
978 // sqlite3_exec() does this, presumably to avoid spinning the parser for
979 // trailing whitespace.
980 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:02981 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:32982 sql++;
983 }
984
985 const base::TimeDelta delta = Now() - before;
986 RecordTimeAndChanges(delta, read_only);
987 }
shess7dbd4dee2015-10-06 17:39:16988
989 // Most calls to Execute() modify the database. The main exceptions would be
990 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
991 // but sometimes don't.
992 ReleaseCacheMemoryIfNeeded(true);
993
shess58b8df82015-06-03 00:19:32994 return rc;
[email protected]eff1fa522011-12-12 23:50:59995}
996
997bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:38998 if (!db_) {
999 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1000 return false;
1001 }
1002
[email protected]eff1fa522011-12-12 23:50:591003 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001004 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581005 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001006
[email protected]28fe0ff2012-02-25 00:40:331007 // This needs to be a FATAL log because the error case of arriving here is
1008 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101009 // a change alters the schema but not all queries adjust. This can happen
1010 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:591011 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:331012 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591013 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561014}
1015
[email protected]5b96f3772010-09-28 16:30:571016bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381017 if (!db_) {
1018 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571019 return false;
[email protected]41a97c812013-02-07 02:35:381020 }
[email protected]5b96f3772010-09-28 16:30:571021
1022 ScopedBusyTimeout busy_timeout(db_);
1023 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591024 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571025}
1026
[email protected]e5ffd0e42009-09-11 21:30:561027bool Connection::HasCachedStatement(const StatementID& id) const {
1028 return statement_cache_.find(id) != statement_cache_.end();
1029}
1030
1031scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1032 const StatementID& id,
1033 const char* sql) {
1034 CachedStatementMap::iterator i = statement_cache_.find(id);
1035 if (i != statement_cache_.end()) {
1036 // Statement is in the cache. It should still be active (we're the only
1037 // one invalidating cached statements, and we'll remove it from the cache
1038 // if we do that. Make sure we reset it before giving out the cached one in
1039 // case it still has some stuff bound.
1040 DCHECK(i->second->is_valid());
1041 sqlite3_reset(i->second->stmt());
1042 return i->second;
1043 }
1044
1045 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1046 if (statement->is_valid())
1047 statement_cache_[id] = statement; // Only cache valid statements.
1048 return statement;
1049}
1050
1051scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1052 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501053 AssertIOAllowed();
1054
[email protected]41a97c812013-02-07 02:35:381055 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561056 if (!db_)
[email protected]41a97c812013-02-07 02:35:381057 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561058
1059 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001060 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1061 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591062 // This is evidence of a syntax error in the incoming SQL.
shess193bfb622015-04-10 22:30:021063 if (!ShouldIgnoreSqliteError(rc))
1064 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001065
1066 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581067 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381068 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561069 }
[email protected]41a97c812013-02-07 02:35:381070 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561071}
1072
[email protected]2eec0a22012-07-24 01:59:581073scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1074 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:381075 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:581076 if (!db_)
[email protected]41a97c812013-02-07 02:35:381077 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:581078
1079 sqlite3_stmt* stmt = NULL;
1080 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1081 if (rc != SQLITE_OK) {
1082 // This is evidence of a syntax error in the incoming SQL.
shess193bfb622015-04-10 22:30:021083 if (!ShouldIgnoreSqliteError(rc))
1084 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:381085 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:581086 }
[email protected]41a97c812013-02-07 02:35:381087 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:581088}
1089
[email protected]92cd00a2013-08-16 11:09:581090std::string Connection::GetSchema() const {
1091 // The ORDER BY should not be necessary, but relying on organic
1092 // order for something like this is questionable.
1093 const char* kSql =
1094 "SELECT type, name, tbl_name, sql "
1095 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1096 Statement statement(GetUntrackedStatement(kSql));
1097
1098 std::string schema;
1099 while (statement.Step()) {
1100 schema += statement.ColumnString(0);
1101 schema += '|';
1102 schema += statement.ColumnString(1);
1103 schema += '|';
1104 schema += statement.ColumnString(2);
1105 schema += '|';
1106 schema += statement.ColumnString(3);
1107 schema += '\n';
1108 }
1109
1110 return schema;
1111}
1112
[email protected]eff1fa522011-12-12 23:50:591113bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501114 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381115 if (!db_) {
1116 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1117 return false;
1118 }
1119
[email protected]eff1fa522011-12-12 23:50:591120 sqlite3_stmt* stmt = NULL;
1121 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1122 return false;
1123
1124 sqlite3_finalize(stmt);
1125 return true;
1126}
1127
[email protected]1ed78a32009-09-15 20:24:171128bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:531129 return DoesTableOrIndexExist(table_name, "table");
1130}
1131
1132bool Connection::DoesIndexExist(const char* index_name) const {
1133 return DoesTableOrIndexExist(index_name, "index");
1134}
1135
1136bool Connection::DoesTableOrIndexExist(
1137 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471138 const char* kSql =
1139 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581140 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471141
1142 // This can happen if the database is corrupt and the error is being ignored
1143 // for testing purposes.
1144 if (!statement.is_valid())
1145 return false;
1146
[email protected]e2cadec82011-12-13 02:00:531147 statement.BindString(0, type);
1148 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331149
[email protected]e5ffd0e42009-09-11 21:30:561150 return statement.Step(); // Table exists if any row was returned.
1151}
1152
1153bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171154 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561155 std::string sql("PRAGMA TABLE_INFO(");
1156 sql.append(table_name);
1157 sql.append(")");
1158
[email protected]2eec0a22012-07-24 01:59:581159 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471160
1161 // This can happen if the database is corrupt and the error is being ignored
1162 // for testing purposes.
1163 if (!statement.is_valid())
1164 return false;
1165
[email protected]e5ffd0e42009-09-11 21:30:561166 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331167 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1168 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561169 return true;
1170 }
1171 return false;
1172}
1173
tfarina720d4f32015-05-11 22:31:261174int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561175 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381176 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561177 return 0;
1178 }
1179 return sqlite3_last_insert_rowid(db_);
1180}
1181
[email protected]1ed78a32009-09-15 20:24:171182int Connection::GetLastChangeCount() const {
1183 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381184 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171185 return 0;
1186 }
1187 return sqlite3_changes(db_);
1188}
1189
[email protected]e5ffd0e42009-09-11 21:30:561190int Connection::GetErrorCode() const {
1191 if (!db_)
1192 return SQLITE_ERROR;
1193 return sqlite3_errcode(db_);
1194}
1195
[email protected]767718e52010-09-21 23:18:491196int Connection::GetLastErrno() const {
1197 if (!db_)
1198 return -1;
1199
1200 int err = 0;
1201 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1202 return -2;
1203
1204 return err;
1205}
1206
[email protected]e5ffd0e42009-09-11 21:30:561207const char* Connection::GetErrorMessage() const {
1208 if (!db_)
1209 return "sql::Connection has no connection.";
1210 return sqlite3_errmsg(db_);
1211}
1212
[email protected]fed734a2013-07-17 04:45:131213bool Connection::OpenInternal(const std::string& file_name,
1214 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501215 AssertIOAllowed();
1216
[email protected]9cfbc922009-11-17 20:13:171217 if (db_) {
[email protected]eff1fa522011-12-12 23:50:591218 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171219 return false;
1220 }
1221
[email protected]a7ec1292013-07-22 22:02:181222 // Make sure sqlite3_initialize() is called before anything else.
1223 InitializeSqlite();
1224
shess58b8df82015-06-03 00:19:321225 // Setup the stats histograms immediately rather than allocating lazily.
1226 // Connections which won't exercise all of these probably shouldn't exist.
1227 if (!histogram_tag_.empty()) {
1228 stats_histogram_ =
1229 base::LinearHistogram::FactoryGet(
1230 "Sqlite.Stats." + histogram_tag_,
1231 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1232 base::HistogramBase::kUmaTargetedHistogramFlag);
1233
1234 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1235 // unreasonable time for any single operation, so there is not much value to
1236 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1237 // things are entirely busted.
1238 commit_time_histogram_ =
1239 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1240
1241 autocommit_time_histogram_ =
1242 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1243
1244 update_time_histogram_ =
1245 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1246
1247 query_time_histogram_ =
1248 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1249 }
1250
[email protected]41a97c812013-02-07 02:35:381251 // If |poisoned_| is set, it means an error handler called
1252 // RazeAndClose(). Until regular Close() is called, the caller
1253 // should be treating the database as open, but is_open() currently
1254 // only considers the sqlite3 handle's state.
1255 // TODO(shess): Revise is_open() to consider poisoned_, and review
1256 // to see if any non-testing code even depends on it.
1257 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161258 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381259
[email protected]765b44502009-10-02 05:01:421260 int err = sqlite3_open(file_name.c_str(), &db_);
1261 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281262 // Extended error codes cannot be enabled until a handle is
1263 // available, fetch manually.
1264 err = sqlite3_extended_errcode(db_);
1265
[email protected]bd2ccdb4a2012-12-07 22:14:501266 // Histogram failures specific to initial open for debugging
1267 // purposes.
[email protected]73fb8d52013-07-24 05:04:281268 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501269
[email protected]2f496b42013-09-26 18:36:581270 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131271 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291272 Close();
[email protected]fed734a2013-07-17 04:45:131273
1274 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1275 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421276 return false;
1277 }
1278
[email protected]81a2a602013-07-17 19:10:361279 // TODO(shess): OS_WIN support?
1280#if defined(OS_POSIX)
1281 if (restrict_to_user_) {
1282 DCHECK_NE(file_name, std::string(":memory"));
1283 base::FilePath file_path(file_name);
1284 int mode = 0;
1285 // TODO(shess): Arguably, failure to retrieve and change
1286 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081287 if (base::GetPosixFilePermissions(file_path, &mode)) {
1288 mode &= base::FILE_PERMISSION_USER_MASK;
1289 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361290
1291 // SQLite sets the permissions on these files from the main
1292 // database on create. Set them here in case they already exist
1293 // at this point. Failure to set these permissions should not
1294 // be fatal unless the file doesn't exist.
1295 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1296 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081297 base::SetPosixFilePermissions(journal_path, mode);
1298 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361299 }
1300 }
1301#endif // defined(OS_POSIX)
1302
[email protected]affa2da2013-06-06 22:20:341303 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1304 // Chromium already depends on small mallocs being efficient, so we disable
1305 // this to avoid the extra memory overhead.
1306 // This must be called immediatly after opening the database before any SQL
1307 // statements are run.
1308 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1309
[email protected]73fb8d52013-07-24 05:04:281310 // Enable extended result codes to provide more color on I/O errors.
1311 // Not having extended result codes is not a fatal problem, as
1312 // Chromium code does not attempt to handle I/O errors anyhow. The
1313 // current implementation always returns SQLITE_OK, the DCHECK is to
1314 // quickly notify someone if SQLite changes.
1315 err = sqlite3_extended_result_codes(db_, 1);
1316 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1317
[email protected]bd2ccdb4a2012-12-07 22:14:501318 // sqlite3_open() does not actually read the database file (unless a
1319 // hot journal is found). Successfully executing this pragma on an
1320 // existing database requires a valid header on page 1.
1321 // TODO(shess): For now, just probing to see what the lay of the
1322 // land is. If it's mostly SQLITE_NOTADB, then the database should
1323 // be razed.
1324 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1325 if (err != SQLITE_OK)
[email protected]73fb8d52013-07-24 05:04:281326 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err);
[email protected]658f8332010-09-18 04:40:431327
[email protected]2e1cee762013-07-09 14:40:001328#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1329 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1330 // REGEXP support. Add it in dynamically.
1331 err = sqlite3IcuInit(db_);
1332 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1333#endif // OS_IOS && USE_SYSTEM_SQLITE
1334
[email protected]5b96f3772010-09-28 16:30:571335 // If indicated, lock up the database before doing anything else, so
1336 // that the following code doesn't have to deal with locking.
1337 // TODO(shess): This code is brittle. Find the cases where code
1338 // doesn't request |exclusive_locking_| and audit that it does the
1339 // right thing with SQLITE_BUSY, and that it doesn't make
1340 // assumptions about who might change things in the database.
1341 // http://crbug.com/56559
1342 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101343 // TODO(shess): This should probably be a failure. Code which
1344 // requests exclusive locking but doesn't get it is almost certain
1345 // to be ill-tested.
1346 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571347 }
1348
[email protected]4e179ba62012-03-17 16:06:471349 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1350 // DELETE (default) - delete -journal file to commit.
1351 // TRUNCATE - truncate -journal file to commit.
1352 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091353 // TRUNCATE should be faster than DELETE because it won't need directory
1354 // changes for each transaction. PERSIST may break the spirit of using
1355 // secure_delete.
1356 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba62012-03-17 16:06:471357
shess7dbd4dee2015-10-06 17:39:161358 // Enable memory-mapped access. This value will be capped by
1359 // SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and 64-bit
1360 // platforms.
1361 mmap_enabled_ = false;
1362 if (!mmap_disabled_)
1363 ignore_result(Execute("PRAGMA mmap_size = 268435456")); // 256MB.
1364 {
1365 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1366 if (s.Step() && s.ColumnInt64(0) > 0)
1367 mmap_enabled_ = true;
1368 }
1369
[email protected]c68ce172011-11-24 22:30:271370 const base::TimeDelta kBusyTimeout =
1371 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1372
[email protected]765b44502009-10-02 05:01:421373 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571374 // Enforce SQLite restrictions on |page_size_|.
1375 DCHECK(!(page_size_ & (page_size_ - 1)))
1376 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241377 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571378 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041379 const std::string sql =
1380 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101381 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421382 }
1383
1384 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041385 const std::string sql =
1386 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101387 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421388 }
1389
[email protected]6e0b1442011-08-09 23:23:581390 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131391 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581392 Close();
[email protected]fed734a2013-07-17 04:45:131393 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1394 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581395 return false;
1396 }
1397
[email protected]765b44502009-10-02 05:01:421398 return true;
1399}
1400
[email protected]e5ffd0e42009-09-11 21:30:561401void Connection::DoRollback() {
1402 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321403
1404 // Collect the rollback time manually, sql::Statement would register it as
1405 // query time only.
1406 const base::TimeTicks before = Now();
1407 rollback.RunWithoutTimers();
1408 const base::TimeDelta delta = Now() - before;
1409
1410 RecordUpdateTime(delta);
1411 RecordOneEvent(EVENT_ROLLBACK);
1412
shess7dbd4dee2015-10-06 17:39:161413 // The cache may have been accumulating dirty pages for commit. Note that in
1414 // some cases sql::Transaction can fire rollback after a database is closed.
1415 if (is_open())
1416 ReleaseCacheMemoryIfNeeded(false);
1417
[email protected]44ad7d902012-03-23 00:09:051418 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561419}
1420
1421void Connection::StatementRefCreated(StatementRef* ref) {
1422 DCHECK(open_statements_.find(ref) == open_statements_.end());
1423 open_statements_.insert(ref);
1424}
1425
1426void Connection::StatementRefDeleted(StatementRef* ref) {
1427 StatementRefSet::iterator i = open_statements_.find(ref);
1428 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:591429 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561430 else
1431 open_statements_.erase(i);
1432}
1433
shess58b8df82015-06-03 00:19:321434void Connection::set_histogram_tag(const std::string& tag) {
1435 DCHECK(!is_open());
1436 histogram_tag_ = tag;
1437}
1438
[email protected]210ce0af2013-05-15 09:10:391439void Connection::AddTaggedHistogram(const std::string& name,
1440 size_t sample) const {
1441 if (histogram_tag_.empty())
1442 return;
1443
1444 // TODO(shess): The histogram macros create a bit of static storage
1445 // for caching the histogram object. This code shouldn't execute
1446 // often enough for such caching to be crucial. If it becomes an
1447 // issue, the object could be cached alongside histogram_prefix_.
1448 std::string full_histogram_name = name + "." + histogram_tag_;
1449 base::HistogramBase* histogram =
1450 base::SparseHistogram::FactoryGet(
1451 full_histogram_name,
1452 base::HistogramBase::kUmaTargetedHistogramFlag);
1453 if (histogram)
1454 histogram->Add(sample);
1455}
1456
[email protected]2f496b42013-09-26 18:36:581457int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) {
[email protected]210ce0af2013-05-15 09:10:391458 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
1459 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141460
1461 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581462 if (!sql && stmt)
1463 sql = stmt->GetSQLStatement();
1464 if (!sql)
1465 sql = "-- unknown";
1466 LOG(ERROR) << histogram_tag_ << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141467 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581468 << ": " << GetErrorMessage()
1469 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141470
[email protected]c3881b372013-05-17 08:39:461471 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561472 // Fire from a copy of the callback in case of reentry into
1473 // re/set_error_callback().
1474 // TODO(shess): <http://crbug.com/254584>
1475 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461476 return err;
1477 }
1478
[email protected]faa604e2009-09-25 22:38:591479 // The default handling is to assert on debug and to ignore on release.
[email protected]74cdede2013-09-25 05:39:571480 if (!ShouldIgnoreSqliteError(err))
[email protected]4350e322013-06-18 22:18:101481 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591482 return err;
1483}
1484
[email protected]579446c2013-12-16 18:36:521485bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1486 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1487}
1488
1489bool Connection::QuickIntegrityCheck() {
1490 std::vector<std::string> messages;
1491 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1492 return false;
1493 return messages.size() == 1 && messages[0] == "ok";
1494}
1495
[email protected]80abf152013-05-22 12:42:421496// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521497bool Connection::IntegrityCheckHelper(
1498 const char* pragma_sql,
1499 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421500 messages->clear();
1501
[email protected]4658e2a02013-06-06 23:05:001502 // This has the side effect of setting SQLITE_RecoveryMode, which
1503 // allows SQLite to process through certain cases of corruption.
1504 // Failing to set this pragma probably means that the database is
1505 // beyond recovery.
1506 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1507 if (!Execute(kWritableSchema))
1508 return false;
1509
1510 bool ret = false;
1511 {
[email protected]579446c2013-12-16 18:36:521512 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001513
1514 // The pragma appears to return all results (up to 100 by default)
1515 // as a single string. This doesn't appear to be an API contract,
1516 // it could return separate lines, so loop _and_ split.
1517 while (stmt.Step()) {
1518 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181519 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1520 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001521 }
1522 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421523 }
[email protected]4658e2a02013-06-06 23:05:001524
1525 // Best effort to put things back as they were before.
1526 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1527 ignore_result(Execute(kNoWritableSchema));
1528
1529 return ret;
[email protected]80abf152013-05-22 12:42:421530}
1531
shess58b8df82015-06-03 00:19:321532base::TimeTicks TimeSource::Now() {
1533 return base::TimeTicks::Now();
1534}
1535
[email protected]e5ffd0e42009-09-11 21:30:561536} // namespace sql