blob: 9daa7d1c3b1c4be221d33ec8aadb15b7d37d2091 [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"
30#include "base/trace_event/process_memory_dump.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
ssid9f8022f2015-10-12 17:49:03257bool Connection::OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
258 base::trace_event::ProcessMemoryDump* pmd) {
259 if (args.level_of_detail ==
260 base::trace_event::MemoryDumpLevelOfDetail::LIGHT ||
261 !db_) {
262 return true;
263 }
264
265 // The high water mark is not tracked for the following usages.
266 int cache_size, dummy_int;
267 sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED, &cache_size, &dummy_int,
268 0 /* resetFlag */);
269 int schema_size;
270 sqlite3_db_status(db_, SQLITE_DBSTATUS_SCHEMA_USED, &schema_size, &dummy_int,
271 0 /* resetFlag */);
272 int statement_size;
273 sqlite3_db_status(db_, SQLITE_DBSTATUS_STMT_USED, &statement_size, &dummy_int,
274 0 /* resetFlag */);
275
276 std::string name = base::StringPrintf(
277 "sqlite/%s_connection/%p",
278 histogram_tag_.empty() ? "Unknown" : histogram_tag_.c_str(), this);
279 base::trace_event::MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(name);
280 dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
281 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
282 cache_size + schema_size + statement_size);
283 dump->AddScalar("cache_size",
284 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
285 cache_size);
286 dump->AddScalar("schema_size",
287 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
288 schema_size);
289 dump->AddScalar("statement_size",
290 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
291 statement_size);
292 return true;
293}
294
shessc8cd2a162015-10-22 20:30:46295void Connection::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
296 AssertIOAllowed();
297
298 std::string debug_info;
299 const int error = (extended_error & 0xFF);
300 if (error == SQLITE_CORRUPT) {
301 debug_info = CollectCorruptionInfo();
302 } else {
303 debug_info = CollectErrorInfo(extended_error, stmt);
304 }
305
306 if (!debug_info.empty() && RegisterIntentToUpload()) {
307 char debug_buf[2000];
308 base::strlcpy(debug_buf, debug_info.c_str(), arraysize(debug_buf));
309 base::debug::Alias(&debug_buf);
310
311 base::debug::DumpWithoutCrashing();
312 }
313}
314
[email protected]4350e322013-06-18 22:18:10315// static
316void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
317 CHECK(current_ignorer_cb_ == NULL);
318 current_ignorer_cb_ = cb;
319}
320
321// static
322void Connection::ResetErrorIgnorer() {
323 CHECK(current_ignorer_cb_);
324 current_ignorer_cb_ = NULL;
325}
326
[email protected]e5ffd0e42009-09-11 21:30:56327bool StatementID::operator<(const StatementID& other) const {
328 if (number_ != other.number_)
329 return number_ < other.number_;
330 return strcmp(str_, other.str_) < 0;
331}
332
[email protected]e5ffd0e42009-09-11 21:30:56333Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38334 sqlite3_stmt* stmt,
335 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56336 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38337 stmt_(stmt),
338 was_valid_(was_valid) {
339 if (connection)
340 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56341}
342
343Connection::StatementRef::~StatementRef() {
344 if (connection_)
345 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38346 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56347}
348
[email protected]41a97c812013-02-07 02:35:38349void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56350 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50351 // Call to AssertIOAllowed() cannot go at the beginning of the function
352 // because Close() is called unconditionally from destructor to clean
353 // connection_. And if this is inactive statement this won't cause any
354 // disk access and destructor most probably will be called on thread
355 // not allowing disk access.
356 // TODO([email protected]): This should move to the beginning
357 // of the function. http://crbug.com/136655.
358 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56359 sqlite3_finalize(stmt_);
360 stmt_ = NULL;
361 }
362 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38363
364 // Forced close is expected to happen from a statement error
365 // handler. In that case maintain the sense of |was_valid_| which
366 // previously held for this ref.
367 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56368}
369
370Connection::Connection()
371 : db_(NULL),
372 page_size_(0),
373 cache_size_(0),
374 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36375 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56376 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50377 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16378 in_memory_(false),
shess58b8df82015-06-03 00:19:32379 poisoned_(false),
shess7dbd4dee2015-10-06 17:39:16380 mmap_disabled_(false),
381 mmap_enabled_(false),
382 total_changes_at_last_release_(0),
shess58b8df82015-06-03 00:19:32383 stats_histogram_(NULL),
384 commit_time_histogram_(NULL),
385 autocommit_time_histogram_(NULL),
386 update_time_histogram_(NULL),
387 query_time_histogram_(NULL),
388 clock_(new TimeSource()) {
ssid9f8022f2015-10-12 17:49:03389 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
primiano186d6bfe2015-10-30 13:21:40390 this, "sql::Connection", nullptr);
[email protected]526b4662013-06-14 04:09:12391}
[email protected]e5ffd0e42009-09-11 21:30:56392
393Connection::~Connection() {
ssid9f8022f2015-10-12 17:49:03394 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
395 this);
[email protected]e5ffd0e42009-09-11 21:30:56396 Close();
397}
398
shess58b8df82015-06-03 00:19:32399void Connection::RecordEvent(Events event, size_t count) {
400 for (size_t i = 0; i < count; ++i) {
401 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
402 }
403
404 if (stats_histogram_) {
405 for (size_t i = 0; i < count; ++i) {
406 stats_histogram_->Add(event);
407 }
408 }
409}
410
411void Connection::RecordCommitTime(const base::TimeDelta& delta) {
412 RecordUpdateTime(delta);
413 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
414 if (commit_time_histogram_)
415 commit_time_histogram_->AddTime(delta);
416}
417
418void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
419 RecordUpdateTime(delta);
420 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
421 if (autocommit_time_histogram_)
422 autocommit_time_histogram_->AddTime(delta);
423}
424
425void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
426 RecordQueryTime(delta);
427 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
428 if (update_time_histogram_)
429 update_time_histogram_->AddTime(delta);
430}
431
432void Connection::RecordQueryTime(const base::TimeDelta& delta) {
433 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
434 if (query_time_histogram_)
435 query_time_histogram_->AddTime(delta);
436}
437
438void Connection::RecordTimeAndChanges(
439 const base::TimeDelta& delta, bool read_only) {
440 if (read_only) {
441 RecordQueryTime(delta);
442 } else {
443 const int changes = sqlite3_changes(db_);
444 if (sqlite3_get_autocommit(db_)) {
445 RecordAutoCommitTime(delta);
446 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
447 } else {
448 RecordUpdateTime(delta);
449 RecordEvent(EVENT_CHANGES, changes);
450 }
451 }
452}
453
[email protected]a3ef4832013-02-02 05:12:33454bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02455 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26456 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49457 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02458 size_t sample = static_cast<size_t>(size_64 / 1024);
459 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
460 base::HistogramBase* histogram =
461 base::Histogram::FactoryGet(
462 full_histogram_name, 1, 1000000, 50,
463 base::HistogramBase::kUmaTargetedHistogramFlag);
464 if (histogram)
465 histogram->Add(sample);
shess9bf2c672015-12-18 01:18:08466 UMA_HISTOGRAM_COUNTS("Sqlite.SizeKB", sample);
[email protected]348ac8f52013-05-21 03:27:02467 }
468 }
469
erg102ceb412015-06-20 01:38:13470 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42471}
[email protected]e5ffd0e42009-09-11 21:30:56472
[email protected]765b44502009-10-02 05:01:42473bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50474 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13475 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56476}
477
[email protected]8d409412013-07-19 18:25:30478bool Connection::OpenTemporary() {
479 return OpenInternal("", NO_RETRY);
480}
481
[email protected]41a97c812013-02-07 02:35:38482void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47483 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
484 // will delete the -journal file. For ChromiumOS or other more
485 // embedded systems, this is probably not appropriate, whereas on
486 // desktop it might make some sense.
487
[email protected]4b350052012-02-24 20:40:48488 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48489
[email protected]41a97c812013-02-07 02:35:38490 // Release cached statements.
491 statement_cache_.clear();
492
493 // With cached statements released, in-use statements will remain.
494 // Closing the database while statements are in use is an API
495 // violation, except for forced close (which happens from within a
496 // statement's error handler).
497 DCHECK(forced || open_statements_.empty());
498
499 // Deactivate any outstanding statements so sqlite3_close() works.
500 for (StatementRefSet::iterator i = open_statements_.begin();
501 i != open_statements_.end(); ++i)
502 (*i)->Close(forced);
503 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48504
[email protected]e5ffd0e42009-09-11 21:30:56505 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50506 // Call to AssertIOAllowed() cannot go at the beginning of the function
507 // because Close() must be called from destructor to clean
508 // statement_cache_, it won't cause any disk access and it most probably
509 // will happen on thread not allowing disk access.
510 // TODO([email protected]): This should move to the beginning
511 // of the function. http://crbug.com/136655.
512 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28513
514 int rc = sqlite3_close(db_);
515 if (rc != SQLITE_OK) {
516 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc);
517 DLOG(FATAL) << "sqlite3_close failed: " << GetErrorMessage();
518 }
[email protected]e5ffd0e42009-09-11 21:30:56519 }
[email protected]fed734a2013-07-17 04:45:13520 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56521}
522
[email protected]41a97c812013-02-07 02:35:38523void Connection::Close() {
524 // If the database was already closed by RazeAndClose(), then no
525 // need to close again. Clear the |poisoned_| bit so that incorrect
526 // API calls are caught.
527 if (poisoned_) {
528 poisoned_ = false;
529 return;
530 }
531
532 CloseInternal(false);
533}
534
[email protected]e5ffd0e42009-09-11 21:30:56535void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50536 AssertIOAllowed();
537
[email protected]e5ffd0e42009-09-11 21:30:56538 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38539 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56540 return;
541 }
542
[email protected]8ada10f2013-12-21 00:42:34543 // Use local settings if provided, otherwise use documented defaults. The
544 // actual results could be fetching via PRAGMA calls.
545 const int page_size = page_size_ ? page_size_ : 1024;
546 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
547 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56548 return;
549
[email protected]8ada10f2013-12-21 00:42:34550 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:34551 sqlite3_int64 file_size = 0;
shess5dac334f2015-11-05 20:47:42552 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
[email protected]8ada10f2013-12-21 00:42:34553 if (rc != SQLITE_OK)
554 return;
555
556 // Don't preload more than the file contains.
557 if (preload_size > file_size)
558 preload_size = file_size;
559
560 scoped_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46561 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34562 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
shessd90aeea82015-11-13 02:24:31563
564 // TODO(shess): Consider calling OnSqliteError().
[email protected]8ada10f2013-12-21 00:42:34565 if (rc != SQLITE_OK)
566 return;
567 }
[email protected]e5ffd0e42009-09-11 21:30:56568}
569
shess7dbd4dee2015-10-06 17:39:16570// SQLite keeps unused pages associated with a connection in a cache. It asks
571// the cache for pages by an id, and if the page is present and the database is
572// unchanged, it considers the content of the page valid and doesn't read it
573// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
574// structures created from the memory map data before consulting the cache. On
575// write SQLite creates a new in-memory page structure, copies the data from the
576// memory map, and later writes it, releasing the updated page back to the
577// cache.
578//
579// This means that in memory-mapped mode, the contents of the cached pages are
580// not re-used for reads, but they are re-used for writes if the re-written page
581// is still in the cache. The implementation of sqlite3_db_release_memory() as
582// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
583// connection, so it should free these pages.
584//
585// Unfortunately, the zero page is also freed. That page is never accessed
586// using memory-mapped I/O, and the cached copy can be re-used after verifying
587// the file change counter on disk. Also, fresh pages from cache receive some
588// pager-level initialization before they can be used. Since the information
589// involved will immediately be accessed in various ways, it is unclear if the
590// additional overhead is material, or just moving processor cache effects
591// around.
592//
593// TODO(shess): It would be better to release the pages immediately when they
594// are no longer needed. This would basically happen after SQLite commits a
595// transaction. I had implemented a pcache wrapper to do this, but it involved
596// layering violations, and it had to be setup before any other sqlite call,
597// which was brittle. Also, for large files it would actually make sense to
598// maintain the existing pcache behavior for blocks past the memory-mapped
599// segment. I think drh would accept a reasonable implementation of the overall
600// concept for upstreaming to SQLite core.
601//
602// TODO(shess): Another possibility would be to set the cache size small, which
603// would keep the zero page around, plus some pre-initialized pages, and SQLite
604// can manage things. The downside is that updates larger than the cache would
605// spill to the journal. That could be compensated by setting cache_spill to
606// false. The downside then is that it allows open-ended use of memory for
607// large transactions.
608//
609// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
610// work. There could be two prepared statements, one for cache_size=1 one for
611// cache_size=goal.
612void Connection::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
613 DCHECK(is_open());
614
615 // If memory-mapping is not enabled, the page cache helps performance.
616 if (!mmap_enabled_)
617 return;
618
619 // On caller request, force the change comparison to fail. Done before the
620 // transaction-nesting test so that the signal can carry to transaction
621 // commit.
622 if (implicit_change_performed)
623 --total_changes_at_last_release_;
624
625 // Cached pages may be re-used within the same transaction.
626 if (transaction_nesting())
627 return;
628
629 // If no changes have been made, skip flushing. This allows the first page of
630 // the database to remain in cache across multiple reads.
631 const int total_changes = sqlite3_total_changes(db_);
632 if (total_changes == total_changes_at_last_release_)
633 return;
634
635 total_changes_at_last_release_ = total_changes;
636 sqlite3_db_release_memory(db_);
637}
638
shessc8cd2a162015-10-22 20:30:46639base::FilePath Connection::DbPath() const {
640 if (!is_open())
641 return base::FilePath();
642
643 const char* path = sqlite3_db_filename(db_, "main");
644 const base::StringPiece db_path(path);
645#if defined(OS_WIN)
646 return base::FilePath(base::UTF8ToWide(db_path));
647#elif defined(OS_POSIX)
648 return base::FilePath(db_path);
649#else
650 NOTREACHED();
651 return base::FilePath();
652#endif
653}
654
655// Data is persisted in a file shared between databases in the same directory.
656// The "sqlite-diag" file contains a dictionary with the version number, and an
657// array of histogram tags for databases which have been dumped.
658bool Connection::RegisterIntentToUpload() const {
659 static const char* kVersionKey = "version";
660 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
661 static int kVersion = 1;
662
663 AssertIOAllowed();
664
665 if (histogram_tag_.empty())
666 return false;
667
668 if (!is_open())
669 return false;
670
671 if (in_memory_)
672 return false;
673
674 const base::FilePath db_path = DbPath();
675 if (db_path.empty())
676 return false;
677
678 // Put the collection of diagnostic data next to the databases. In most
679 // cases, this is the profile directory, but safe-browsing stores a Cookies
680 // file in the directory above the profile directory.
681 base::FilePath breadcrumb_path(
682 db_path.DirName().Append(FILE_PATH_LITERAL("sqlite-diag")));
683
684 // Lock against multiple updates to the diagnostics file. This code should
685 // seldom be called in the first place, and when called it should seldom be
686 // called for multiple databases, and when called for multiple databases there
687 // is _probably_ something systemic wrong with the user's system. So the lock
688 // should never be contended, but when it is the database experience is
689 // already bad.
690 base::AutoLock lock(g_sqlite_init_lock.Get());
691
692 scoped_ptr<base::Value> root;
693 if (!base::PathExists(breadcrumb_path)) {
694 scoped_ptr<base::DictionaryValue> root_dict(new base::DictionaryValue());
695 root_dict->SetInteger(kVersionKey, kVersion);
696
697 scoped_ptr<base::ListValue> dumps(new base::ListValue);
698 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50699 root_dict->Set(kDiagnosticDumpsKey, std::move(dumps));
shessc8cd2a162015-10-22 20:30:46700
dchenge48600452015-12-28 02:24:50701 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46702 } else {
703 // Failure to read a valid dictionary implies that something is going wrong
704 // on the system.
705 JSONFileValueDeserializer deserializer(breadcrumb_path);
706 scoped_ptr<base::Value> read_root(
707 deserializer.Deserialize(nullptr, nullptr));
708 if (!read_root.get())
709 return false;
710 scoped_ptr<base::DictionaryValue> root_dict =
dchenge48600452015-12-28 02:24:50711 base::DictionaryValue::From(std::move(read_root));
shessc8cd2a162015-10-22 20:30:46712 if (!root_dict)
713 return false;
714
715 // Don't upload if the version is missing or newer.
716 int version = 0;
717 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
718 return false;
719
720 base::ListValue* dumps = nullptr;
721 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
722 return false;
723
724 const size_t size = dumps->GetSize();
725 for (size_t i = 0; i < size; ++i) {
726 std::string s;
727
728 // Don't upload if the value isn't a string, or indicates a prior upload.
729 if (!dumps->GetString(i, &s) || s == histogram_tag_)
730 return false;
731 }
732
733 // Record intention to proceed with upload.
734 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50735 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46736 }
737
738 const base::FilePath breadcrumb_new =
739 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
740 base::DeleteFile(breadcrumb_new, false);
741
742 // No upload if the breadcrumb file cannot be updated.
743 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
744 // the data on disk. For now, losing the data is not a big problem, so the
745 // sync overhead would probably not be worth it.
746 JSONFileValueSerializer serializer(breadcrumb_new);
747 if (!serializer.Serialize(*root))
748 return false;
749 if (!base::PathExists(breadcrumb_new))
750 return false;
751 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
752 base::DeleteFile(breadcrumb_new, false);
753 return false;
754 }
755
756 return true;
757}
758
759std::string Connection::CollectErrorInfo(int error, Statement* stmt) const {
760 // Buffer for accumulating debugging info about the error. Place
761 // more-relevant information earlier, in case things overflow the
762 // fixed-size reporting buffer.
763 std::string debug_info;
764
765 // The error message from the failed operation.
766 base::StringAppendF(&debug_info, "db error: %d/%s\n",
767 GetErrorCode(), GetErrorMessage());
768
769 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
770 // reading code does not entirely convince me. Remove if they turn out to be
771 // the same.
772 if (error != GetErrorCode())
773 base::StringAppendF(&debug_info, "reported error: %d\n", error);
774
775 // System error information. Interpretation of Windows errors is different
776 // from posix.
777#if defined(OS_WIN)
778 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
779#elif defined(OS_POSIX)
780 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
781#else
782 NOTREACHED(); // Add appropriate log info.
783#endif
784
785 if (stmt) {
786 base::StringAppendF(&debug_info, "statement: %s\n",
787 stmt->GetSQLStatement());
788 } else {
789 base::StringAppendF(&debug_info, "statement: NULL\n");
790 }
791
792 // SQLITE_ERROR often indicates some sort of mismatch between the statement
793 // and the schema, possibly due to a failed schema migration.
794 if (error == SQLITE_ERROR) {
795 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
796 sqlite3_stmt* s;
797 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
798 if (rc == SQLITE_OK) {
799 rc = sqlite3_step(s);
800 if (rc == SQLITE_ROW) {
801 base::StringAppendF(&debug_info, "version: %d\n",
802 sqlite3_column_int(s, 0));
803 } else if (rc == SQLITE_DONE) {
804 debug_info += "version: none\n";
805 } else {
806 base::StringAppendF(&debug_info, "version: error %d\n", rc);
807 }
808 sqlite3_finalize(s);
809 } else {
810 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
811 }
812
813 debug_info += "schema:\n";
814
815 // sqlite_master has columns:
816 // type - "index" or "table".
817 // name - name of created element.
818 // tbl_name - name of element, or target table in case of index.
819 // rootpage - root page of the element in database file.
820 // sql - SQL to create the element.
821 // In general, the |sql| column is sufficient to derive the other columns.
822 // |rootpage| is not interesting for debugging, without the contents of the
823 // database. The COALESCE is because certain automatic elements will have a
824 // |name| but no |sql|,
825 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
826 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
827 if (rc == SQLITE_OK) {
828 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
829 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
830 }
831 if (rc != SQLITE_DONE)
832 base::StringAppendF(&debug_info, "error %d\n", rc);
833 sqlite3_finalize(s);
834 } else {
835 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
836 }
837 }
838
839 return debug_info;
840}
841
842// TODO(shess): Since this is only called in an error situation, it might be
843// prudent to rewrite in terms of SQLite API calls, and mark the function const.
844std::string Connection::CollectCorruptionInfo() {
845 AssertIOAllowed();
846
847 // If the file cannot be accessed it is unlikely that an integrity check will
848 // turn up actionable information.
849 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19850 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46851 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
852 return std::string();
853
854 // Buffer for accumulating debugging info about the error. Place
855 // more-relevant information earlier, in case things overflow the
856 // fixed-size reporting buffer.
857 std::string debug_info;
858 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
859 db_size);
860
861 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19862 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46863 if (db_size > kMaxIntegrityCheckSize) {
864 debug_info += "integrity_check skipped due to size\n";
865 } else {
866 std::vector<std::string> messages;
867
868 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
869 // into a string. Probably should be refactored.
870 const base::TimeTicks before = base::TimeTicks::Now();
871 FullIntegrityCheck(&messages);
872 base::StringAppendF(
873 &debug_info,
874 "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
875 (base::TimeTicks::Now() - before).InMilliseconds(),
876 messages.size());
877
878 // SQLite returns up to 100 messages by default, trim deeper to
879 // keep close to the 2000-character size limit for dumping.
880 const size_t kMaxMessages = 20;
881 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
882 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
883 }
884 }
885
886 return debug_info;
887}
888
shessd90aeea82015-11-13 02:24:31889size_t Connection::GetAppropriateMmapSize() {
890 AssertIOAllowed();
891
shessd90aeea82015-11-13 02:24:31892#if defined(OS_IOS)
893 // iOS SQLite does not support memory mapping.
894 return 0;
895#endif
896
shess9bf2c672015-12-18 01:18:08897 // How much to map if no errors are found. 50MB encompasses the 99th
898 // percentile of Chrome databases in the wild, so this should be good.
899 const size_t kMmapEverything = 256 * 1024 * 1024;
900
901 // If the database doesn't have a place to track progress, assume the best.
902 // This will happen when new databases are created, or if a database doesn't
903 // use a meta table. sql::MetaTable::Init() will preload kMmapSuccess.
904 // TODO(shess): Databases not using meta include:
905 // DOMStorageDatabase (localstorage)
906 // ActivityDatabase (extensions activity log)
907 // PredictorDatabase (prefetch and autocomplete predictor data)
908 // SyncDirectory (sync metadata storage)
909 // For now, these all have mmap disabled to allow other databases to get the
910 // default-enable path. sqlite-diag could be an alternative for all but
911 // DOMStorageDatabase, which creates many small databases.
912 // http://crbug.com/537742
913 if (!MetaTable::DoesTableExist(this)) {
shessd90aeea82015-11-13 02:24:31914 RecordOneEvent(EVENT_MMAP_META_MISSING);
shess9bf2c672015-12-18 01:18:08915 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31916 }
917
shess9bf2c672015-12-18 01:18:08918 int64_t mmap_ofs = 0;
919 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
920 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
921 return 0;
shessd90aeea82015-11-13 02:24:31922 }
923
924 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08925 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31926 RecordOneEvent(EVENT_MMAP_FAILED);
927 return 0;
shess9bf2c672015-12-18 01:18:08928 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31929 // Continue reading from previous offset.
930 DCHECK_GE(mmap_ofs, 0);
931
932 // TODO(shess): Could this reading code be shared with Preload()? It would
933 // require locking twice (this code wouldn't be able to access |db_size| so
934 // the helper would have to return amount read).
935
936 // Read more of the database looking for errors. The VFS interface is used
937 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
938 // to limit checking to 20MB per run of Chromium.
939 sqlite3_file* file = NULL;
940 sqlite3_int64 db_size = 0;
941 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
942 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
943 return 0;
944 }
945
946 // Read the data left, or |g_reads_allowed|, whichever is smaller.
947 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
948 // in a single Chromium run.
949 sqlite3_int64 amount = db_size - mmap_ofs;
950 if (amount < 0)
951 amount = 0;
952 if (amount > 0) {
953 base::AutoLock lock(g_sqlite_init_lock.Get());
954 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
955 if (g_reads_allowed < amount)
956 amount = g_reads_allowed;
957 g_reads_allowed -= amount;
958 }
959
960 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
961 // database was truncated after a previous pass.
962 if (amount <= 0 && mmap_ofs < db_size) {
963 DCHECK_EQ(0, amount);
964 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
965 } else {
966 static const int kPageSize = 4096;
967 char buf[kPageSize];
968 while (amount > 0) {
969 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
970 if (rc == SQLITE_OK) {
971 mmap_ofs += sizeof(buf);
972 amount -= sizeof(buf);
973 } else if (rc == SQLITE_IOERR_SHORT_READ) {
974 // Reached EOF for a database with page size < |kPageSize|.
975 mmap_ofs = db_size;
976 break;
977 } else {
978 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08979 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31980 break;
981 }
982 }
983
984 // Log these events after update to distinguish meta update failure.
985 Events event;
986 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08987 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31988 event = EVENT_MMAP_SUCCESS_NEW;
989 } else if (mmap_ofs > 0) {
990 event = EVENT_MMAP_SUCCESS_PARTIAL;
991 } else {
shess9bf2c672015-12-18 01:18:08992 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31993 event = EVENT_MMAP_FAILED_NEW;
994 }
995
shess9bf2c672015-12-18 01:18:08996 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
shessd90aeea82015-11-13 02:24:31997 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
998 return 0;
999 }
1000
1001 RecordOneEvent(event);
1002 }
1003 }
1004
shess9bf2c672015-12-18 01:18:081005 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:311006 return 0;
shess9bf2c672015-12-18 01:18:081007 if (mmap_ofs == MetaTable::kMmapSuccess)
1008 return kMmapEverything;
shessd90aeea82015-11-13 02:24:311009 return mmap_ofs;
1010}
1011
[email protected]be7995f12013-07-18 18:49:141012void Connection::TrimMemory(bool aggressively) {
1013 if (!db_)
1014 return;
1015
1016 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
1017 int original_cache_size;
1018 {
1019 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
1020 if (!sql_get_original.Step()) {
1021 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
1022 return;
1023 }
1024 original_cache_size = sql_get_original.ColumnInt(0);
1025 }
1026 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
1027
1028 // Force sqlite to try to reduce page cache usage.
1029 const std::string sql_shrink =
1030 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
1031 if (!Execute(sql_shrink.c_str()))
1032 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
1033
1034 // Restore cache size.
1035 const std::string sql_restore =
1036 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
1037 if (!Execute(sql_restore.c_str()))
1038 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
1039}
1040
[email protected]8e0c01282012-04-06 19:36:491041// Create an in-memory database with the existing database's page
1042// size, then backup that database over the existing database.
1043bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:501044 AssertIOAllowed();
1045
[email protected]8e0c01282012-04-06 19:36:491046 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381047 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491048 return false;
1049 }
1050
1051 if (transaction_nesting_ > 0) {
1052 DLOG(FATAL) << "Cannot raze within a transaction";
1053 return false;
1054 }
1055
1056 sql::Connection null_db;
1057 if (!null_db.OpenInMemory()) {
1058 DLOG(FATAL) << "Unable to open in-memory database.";
1059 return false;
1060 }
1061
[email protected]6d42f152012-11-10 00:38:241062 if (page_size_) {
1063 // Enforce SQLite restrictions on |page_size_|.
1064 DCHECK(!(page_size_ & (page_size_ - 1)))
1065 << " page_size_ " << page_size_ << " is not a power of two.";
1066 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1067 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041068 const std::string sql =
1069 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:421070 if (!null_db.Execute(sql.c_str()))
1071 return false;
1072 }
1073
[email protected]6d42f152012-11-10 00:38:241074#if defined(OS_ANDROID)
1075 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1076 // in-memory databases do not respect this define.
1077 // TODO(shess): Figure out a way to set this without using platform
1078 // specific code. AFAICT from sqlite3.c, the only way to do it
1079 // would be to create an actual filesystem database, which is
1080 // unfortunate.
1081 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1082 return false;
1083#endif
[email protected]8e0c01282012-04-06 19:36:491084
1085 // The page size doesn't take effect until a database has pages, and
1086 // at this point the null database has none. Changing the schema
1087 // version will create the first page. This will not affect the
1088 // schema version in the resulting database, as SQLite's backup
1089 // implementation propagates the schema version from the original
1090 // connection to the new version of the database, incremented by one
1091 // so that other readers see the schema change and act accordingly.
1092 if (!null_db.Execute("PRAGMA schema_version = 1"))
1093 return false;
1094
[email protected]6d42f152012-11-10 00:38:241095 // SQLite tracks the expected number of database pages in the first
1096 // page, and if it does not match the total retrieved from a
1097 // filesystem call, treats the database as corrupt. This situation
1098 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1099 // used to hint to SQLite to soldier on in that case, specifically
1100 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1101 // sqlite3.c lockBtree().]
1102 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1103 // page_size" can be used to query such a database.
1104 ScopedWritableSchema writable_schema(db_);
1105
[email protected]7bae5742013-07-10 20:46:161106 const char* kMain = "main";
1107 int rc = BackupDatabase(null_db.db_, db_, kMain);
1108 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:491109
1110 // The destination database was locked.
1111 if (rc == SQLITE_BUSY) {
1112 return false;
1113 }
1114
[email protected]7bae5742013-07-10 20:46:161115 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1116 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1117 // isn't even big enough for one page. Either way, reach in and
1118 // truncate it before trying again.
1119 // TODO(shess): Maybe it would be worthwhile to just truncate from
1120 // the get-go?
1121 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
1122 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:341123 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161124 if (rc != SQLITE_OK) {
1125 DLOG(FATAL) << "Failure getting file handle.";
1126 return false;
[email protected]7bae5742013-07-10 20:46:161127 }
1128
1129 rc = file->pMethods->xTruncate(file, 0);
1130 if (rc != SQLITE_OK) {
1131 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
1132 DLOG(FATAL) << "Failed to truncate file.";
1133 return false;
1134 }
1135
1136 rc = BackupDatabase(null_db.db_, db_, kMain);
1137 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
1138
1139 if (rc != SQLITE_DONE) {
1140 DLOG(FATAL) << "Failed retrying Raze().";
1141 }
1142 }
1143
[email protected]8e0c01282012-04-06 19:36:491144 // The entire database should have been backed up.
1145 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:161146 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:491147 DLOG(FATAL) << "Unable to copy entire null database.";
1148 return false;
1149 }
1150
[email protected]8e0c01282012-04-06 19:36:491151 return true;
1152}
1153
1154bool Connection::RazeWithTimout(base::TimeDelta timeout) {
1155 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381156 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491157 return false;
1158 }
1159
1160 ScopedBusyTimeout busy_timeout(db_);
1161 busy_timeout.SetTimeout(timeout);
1162 return Raze();
1163}
1164
[email protected]41a97c812013-02-07 02:35:381165bool Connection::RazeAndClose() {
1166 if (!db_) {
1167 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
1168 return false;
1169 }
1170
1171 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301172 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381173
1174 bool result = Raze();
1175
1176 CloseInternal(true);
1177
1178 // Mark the database so that future API calls fail appropriately,
1179 // but don't DCHECK (because after calling this function they are
1180 // expected to fail).
1181 poisoned_ = true;
1182
1183 return result;
1184}
1185
[email protected]8d409412013-07-19 18:25:301186void Connection::Poison() {
1187 if (!db_) {
1188 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
1189 return;
1190 }
1191
1192 RollbackAllTransactions();
1193 CloseInternal(true);
1194
1195 // Mark the database so that future API calls fail appropriately,
1196 // but don't DCHECK (because after calling this function they are
1197 // expected to fail).
1198 poisoned_ = true;
1199}
1200
[email protected]8d2e39e2013-06-24 05:55:081201// TODO(shess): To the extent possible, figure out the optimal
1202// ordering for these deletes which will prevent other connections
1203// from seeing odd behavior. For instance, it may be necessary to
1204// manually lock the main database file in a SQLite-compatible fashion
1205// (to prevent other processes from opening it), then delete the
1206// journal files, then delete the main database file. Another option
1207// might be to lock the main database file and poison the header with
1208// junk to prevent other processes from opening it successfully (like
1209// Gears "SQLite poison 3" trick).
1210//
1211// static
1212bool Connection::Delete(const base::FilePath& path) {
1213 base::ThreadRestrictions::AssertIOAllowed();
1214
1215 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
1216 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
1217
erg102ceb412015-06-20 01:38:131218 std::string journal_str = AsUTF8ForSQL(journal_path);
1219 std::string wal_str = AsUTF8ForSQL(wal_path);
1220 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081221
shess702467622015-09-16 19:04:551222 // Make sure sqlite3_initialize() is called before anything else.
1223 InitializeSqlite();
1224
erg102ceb412015-06-20 01:38:131225 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
1226 CHECK(vfs);
1227 CHECK(vfs->xDelete);
1228 CHECK(vfs->xAccess);
1229
1230 // We only work with unix, win32 and mojo filesystems. If you're trying to
1231 // use this code with any other VFS, you're not in a good place.
1232 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1233 strncmp(vfs->zName, "win32", 5) == 0 ||
1234 strcmp(vfs->zName, "mojo") == 0);
1235
1236 vfs->xDelete(vfs, journal_str.c_str(), 0);
1237 vfs->xDelete(vfs, wal_str.c_str(), 0);
1238 vfs->xDelete(vfs, path_str.c_str(), 0);
1239
1240 int journal_exists = 0;
1241 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
1242 &journal_exists);
1243
1244 int wal_exists = 0;
1245 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
1246 &wal_exists);
1247
1248 int path_exists = 0;
1249 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
1250 &path_exists);
1251
1252 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081253}
1254
[email protected]e5ffd0e42009-09-11 21:30:561255bool Connection::BeginTransaction() {
1256 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331257 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561258
1259 // When we're going to rollback, fail on this begin and don't actually
1260 // mark us as entering the nested transaction.
1261 return false;
1262 }
1263
1264 bool success = true;
1265 if (!transaction_nesting_) {
1266 needs_rollback_ = false;
1267
1268 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321269 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591270 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561271 return false;
1272 }
1273 transaction_nesting_++;
1274 return success;
1275}
1276
1277void Connection::RollbackTransaction() {
1278 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:381279 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561280 return;
1281 }
1282
1283 transaction_nesting_--;
1284
1285 if (transaction_nesting_ > 0) {
1286 // Mark the outermost transaction as needing rollback.
1287 needs_rollback_ = true;
1288 return;
1289 }
1290
1291 DoRollback();
1292}
1293
1294bool Connection::CommitTransaction() {
1295 if (!transaction_nesting_) {
shess90244e12015-11-09 22:08:181296 DLOG_IF(FATAL, !poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561297 return false;
1298 }
1299 transaction_nesting_--;
1300
1301 if (transaction_nesting_ > 0) {
1302 // Mark any nested transactions as failing after we've already got one.
1303 return !needs_rollback_;
1304 }
1305
1306 if (needs_rollback_) {
1307 DoRollback();
1308 return false;
1309 }
1310
1311 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321312
1313 // Collect the commit time manually, sql::Statement would register it as query
1314 // time only.
1315 const base::TimeTicks before = Now();
1316 bool ret = commit.RunWithoutTimers();
1317 const base::TimeDelta delta = Now() - before;
1318
1319 RecordCommitTime(delta);
1320 RecordOneEvent(EVENT_COMMIT);
1321
shess7dbd4dee2015-10-06 17:39:161322 // Release dirty cache pages after the transaction closes.
1323 ReleaseCacheMemoryIfNeeded(false);
1324
shess58b8df82015-06-03 00:19:321325 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561326}
1327
[email protected]8d409412013-07-19 18:25:301328void Connection::RollbackAllTransactions() {
1329 if (transaction_nesting_ > 0) {
1330 transaction_nesting_ = 0;
1331 DoRollback();
1332 }
1333}
1334
1335bool Connection::AttachDatabase(const base::FilePath& other_db_path,
1336 const char* attachment_point) {
1337 DCHECK(ValidAttachmentPoint(attachment_point));
1338
1339 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1340#if OS_WIN
1341 s.BindString16(0, other_db_path.value());
1342#else
1343 s.BindString(0, other_db_path.value());
1344#endif
1345 s.BindString(1, attachment_point);
1346 return s.Run();
1347}
1348
1349bool Connection::DetachDatabase(const char* attachment_point) {
1350 DCHECK(ValidAttachmentPoint(attachment_point));
1351
1352 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1353 s.BindString(0, attachment_point);
1354 return s.Run();
1355}
1356
shess58b8df82015-06-03 00:19:321357// TODO(shess): Consider changing this to execute exactly one statement. If a
1358// caller wishes to execute multiple statements, that should be explicit, and
1359// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591360int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501361 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381362 if (!db_) {
1363 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1364 return SQLITE_ERROR;
1365 }
shess58b8df82015-06-03 00:19:321366 DCHECK(sql);
1367
1368 RecordOneEvent(EVENT_EXECUTE);
1369 int rc = SQLITE_OK;
1370 while ((rc == SQLITE_OK) && *sql) {
1371 sqlite3_stmt *stmt = NULL;
1372 const char *leftover_sql;
1373
1374 const base::TimeTicks before = Now();
1375 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1376 sql = leftover_sql;
1377
1378 // Stop if an error is encountered.
1379 if (rc != SQLITE_OK)
1380 break;
1381
1382 // This happens if |sql| originally only contained comments or whitespace.
1383 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1384 // extraneous comments and whitespace in the SQL statements increases
1385 // runtime cost and can easily be shifted out to the C++ layer.
1386 if (!stmt)
1387 continue;
1388
1389 // Save for use after statement is finalized.
1390 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1391
1392 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1393 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1394 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1395 // is the only legitimate case for this.
1396 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1397 }
1398
1399 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1400 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1401 rc = sqlite3_finalize(stmt);
1402 if (rc == SQLITE_OK)
1403 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1404
1405 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1406 // trailing whitespace.
1407 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021408 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321409 sql++;
1410 }
1411
1412 const base::TimeDelta delta = Now() - before;
1413 RecordTimeAndChanges(delta, read_only);
1414 }
shess7dbd4dee2015-10-06 17:39:161415
1416 // Most calls to Execute() modify the database. The main exceptions would be
1417 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1418 // but sometimes don't.
1419 ReleaseCacheMemoryIfNeeded(true);
1420
shess58b8df82015-06-03 00:19:321421 return rc;
[email protected]eff1fa522011-12-12 23:50:591422}
1423
1424bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381425 if (!db_) {
1426 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1427 return false;
1428 }
1429
[email protected]eff1fa522011-12-12 23:50:591430 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001431 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581432 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001433
[email protected]28fe0ff2012-02-25 00:40:331434 // This needs to be a FATAL log because the error case of arriving here is
1435 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101436 // a change alters the schema but not all queries adjust. This can happen
1437 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:591438 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:331439 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591440 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561441}
1442
[email protected]5b96f3772010-09-28 16:30:571443bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381444 if (!db_) {
1445 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571446 return false;
[email protected]41a97c812013-02-07 02:35:381447 }
[email protected]5b96f3772010-09-28 16:30:571448
1449 ScopedBusyTimeout busy_timeout(db_);
1450 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591451 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571452}
1453
[email protected]e5ffd0e42009-09-11 21:30:561454bool Connection::HasCachedStatement(const StatementID& id) const {
1455 return statement_cache_.find(id) != statement_cache_.end();
1456}
1457
1458scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1459 const StatementID& id,
1460 const char* sql) {
1461 CachedStatementMap::iterator i = statement_cache_.find(id);
1462 if (i != statement_cache_.end()) {
1463 // Statement is in the cache. It should still be active (we're the only
1464 // one invalidating cached statements, and we'll remove it from the cache
1465 // if we do that. Make sure we reset it before giving out the cached one in
1466 // case it still has some stuff bound.
1467 DCHECK(i->second->is_valid());
1468 sqlite3_reset(i->second->stmt());
1469 return i->second;
1470 }
1471
1472 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1473 if (statement->is_valid())
1474 statement_cache_[id] = statement; // Only cache valid statements.
1475 return statement;
1476}
1477
1478scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1479 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501480 AssertIOAllowed();
1481
[email protected]41a97c812013-02-07 02:35:381482 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561483 if (!db_)
[email protected]41a97c812013-02-07 02:35:381484 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561485
1486 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001487 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1488 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591489 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061490 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021491 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001492
1493 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581494 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381495 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561496 }
[email protected]41a97c812013-02-07 02:35:381497 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561498}
1499
shessf7e988f2015-11-13 00:41:061500// TODO(shess): Unify this with GetUniqueStatement(). The only difference that
1501// seems legitimate is not passing |this| to StatementRef.
[email protected]2eec0a22012-07-24 01:59:581502scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1503 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:381504 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:581505 if (!db_)
[email protected]41a97c812013-02-07 02:35:381506 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:581507
1508 sqlite3_stmt* stmt = NULL;
1509 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1510 if (rc != SQLITE_OK) {
1511 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061512 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021513 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:381514 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:581515 }
[email protected]41a97c812013-02-07 02:35:381516 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:581517}
1518
[email protected]92cd00a2013-08-16 11:09:581519std::string Connection::GetSchema() const {
1520 // The ORDER BY should not be necessary, but relying on organic
1521 // order for something like this is questionable.
1522 const char* kSql =
1523 "SELECT type, name, tbl_name, sql "
1524 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1525 Statement statement(GetUntrackedStatement(kSql));
1526
1527 std::string schema;
1528 while (statement.Step()) {
1529 schema += statement.ColumnString(0);
1530 schema += '|';
1531 schema += statement.ColumnString(1);
1532 schema += '|';
1533 schema += statement.ColumnString(2);
1534 schema += '|';
1535 schema += statement.ColumnString(3);
1536 schema += '\n';
1537 }
1538
1539 return schema;
1540}
1541
[email protected]eff1fa522011-12-12 23:50:591542bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501543 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381544 if (!db_) {
1545 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1546 return false;
1547 }
1548
[email protected]eff1fa522011-12-12 23:50:591549 sqlite3_stmt* stmt = NULL;
1550 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1551 return false;
1552
1553 sqlite3_finalize(stmt);
1554 return true;
1555}
1556
[email protected]1ed78a32009-09-15 20:24:171557bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:531558 return DoesTableOrIndexExist(table_name, "table");
1559}
1560
1561bool Connection::DoesIndexExist(const char* index_name) const {
1562 return DoesTableOrIndexExist(index_name, "index");
1563}
1564
1565bool Connection::DoesTableOrIndexExist(
1566 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471567 const char* kSql =
1568 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581569 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471570
1571 // This can happen if the database is corrupt and the error is being ignored
1572 // for testing purposes.
1573 if (!statement.is_valid())
1574 return false;
1575
[email protected]e2cadec82011-12-13 02:00:531576 statement.BindString(0, type);
1577 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331578
[email protected]e5ffd0e42009-09-11 21:30:561579 return statement.Step(); // Table exists if any row was returned.
1580}
1581
1582bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171583 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561584 std::string sql("PRAGMA TABLE_INFO(");
1585 sql.append(table_name);
1586 sql.append(")");
1587
[email protected]2eec0a22012-07-24 01:59:581588 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471589
1590 // This can happen if the database is corrupt and the error is being ignored
1591 // for testing purposes.
1592 if (!statement.is_valid())
1593 return false;
1594
[email protected]e5ffd0e42009-09-11 21:30:561595 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331596 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1597 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561598 return true;
1599 }
1600 return false;
1601}
1602
tfarina720d4f32015-05-11 22:31:261603int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561604 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381605 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561606 return 0;
1607 }
1608 return sqlite3_last_insert_rowid(db_);
1609}
1610
[email protected]1ed78a32009-09-15 20:24:171611int Connection::GetLastChangeCount() const {
1612 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381613 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171614 return 0;
1615 }
1616 return sqlite3_changes(db_);
1617}
1618
[email protected]e5ffd0e42009-09-11 21:30:561619int Connection::GetErrorCode() const {
1620 if (!db_)
1621 return SQLITE_ERROR;
1622 return sqlite3_errcode(db_);
1623}
1624
[email protected]767718e52010-09-21 23:18:491625int Connection::GetLastErrno() const {
1626 if (!db_)
1627 return -1;
1628
1629 int err = 0;
1630 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1631 return -2;
1632
1633 return err;
1634}
1635
[email protected]e5ffd0e42009-09-11 21:30:561636const char* Connection::GetErrorMessage() const {
1637 if (!db_)
1638 return "sql::Connection has no connection.";
1639 return sqlite3_errmsg(db_);
1640}
1641
[email protected]fed734a2013-07-17 04:45:131642bool Connection::OpenInternal(const std::string& file_name,
1643 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501644 AssertIOAllowed();
1645
[email protected]9cfbc922009-11-17 20:13:171646 if (db_) {
[email protected]eff1fa522011-12-12 23:50:591647 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171648 return false;
1649 }
1650
[email protected]a7ec1292013-07-22 22:02:181651 // Make sure sqlite3_initialize() is called before anything else.
1652 InitializeSqlite();
1653
shess58b8df82015-06-03 00:19:321654 // Setup the stats histograms immediately rather than allocating lazily.
1655 // Connections which won't exercise all of these probably shouldn't exist.
1656 if (!histogram_tag_.empty()) {
1657 stats_histogram_ =
1658 base::LinearHistogram::FactoryGet(
1659 "Sqlite.Stats." + histogram_tag_,
1660 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1661 base::HistogramBase::kUmaTargetedHistogramFlag);
1662
1663 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1664 // unreasonable time for any single operation, so there is not much value to
1665 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1666 // things are entirely busted.
1667 commit_time_histogram_ =
1668 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1669
1670 autocommit_time_histogram_ =
1671 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1672
1673 update_time_histogram_ =
1674 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1675
1676 query_time_histogram_ =
1677 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1678 }
1679
[email protected]41a97c812013-02-07 02:35:381680 // If |poisoned_| is set, it means an error handler called
1681 // RazeAndClose(). Until regular Close() is called, the caller
1682 // should be treating the database as open, but is_open() currently
1683 // only considers the sqlite3 handle's state.
1684 // TODO(shess): Revise is_open() to consider poisoned_, and review
1685 // to see if any non-testing code even depends on it.
1686 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161687 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381688
[email protected]765b44502009-10-02 05:01:421689 int err = sqlite3_open(file_name.c_str(), &db_);
1690 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281691 // Extended error codes cannot be enabled until a handle is
1692 // available, fetch manually.
1693 err = sqlite3_extended_errcode(db_);
1694
[email protected]bd2ccdb4a2012-12-07 22:14:501695 // Histogram failures specific to initial open for debugging
1696 // purposes.
[email protected]73fb8d52013-07-24 05:04:281697 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501698
[email protected]2f496b42013-09-26 18:36:581699 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131700 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291701 Close();
[email protected]fed734a2013-07-17 04:45:131702
1703 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1704 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421705 return false;
1706 }
1707
[email protected]81a2a602013-07-17 19:10:361708 // TODO(shess): OS_WIN support?
1709#if defined(OS_POSIX)
1710 if (restrict_to_user_) {
1711 DCHECK_NE(file_name, std::string(":memory"));
1712 base::FilePath file_path(file_name);
1713 int mode = 0;
1714 // TODO(shess): Arguably, failure to retrieve and change
1715 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081716 if (base::GetPosixFilePermissions(file_path, &mode)) {
1717 mode &= base::FILE_PERMISSION_USER_MASK;
1718 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361719
1720 // SQLite sets the permissions on these files from the main
1721 // database on create. Set them here in case they already exist
1722 // at this point. Failure to set these permissions should not
1723 // be fatal unless the file doesn't exist.
1724 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1725 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081726 base::SetPosixFilePermissions(journal_path, mode);
1727 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361728 }
1729 }
1730#endif // defined(OS_POSIX)
1731
[email protected]affa2da2013-06-06 22:20:341732 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1733 // Chromium already depends on small mallocs being efficient, so we disable
1734 // this to avoid the extra memory overhead.
1735 // This must be called immediatly after opening the database before any SQL
1736 // statements are run.
1737 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1738
[email protected]73fb8d52013-07-24 05:04:281739 // Enable extended result codes to provide more color on I/O errors.
1740 // Not having extended result codes is not a fatal problem, as
1741 // Chromium code does not attempt to handle I/O errors anyhow. The
1742 // current implementation always returns SQLITE_OK, the DCHECK is to
1743 // quickly notify someone if SQLite changes.
1744 err = sqlite3_extended_result_codes(db_, 1);
1745 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1746
[email protected]bd2ccdb4a2012-12-07 22:14:501747 // sqlite3_open() does not actually read the database file (unless a
1748 // hot journal is found). Successfully executing this pragma on an
1749 // existing database requires a valid header on page 1.
1750 // TODO(shess): For now, just probing to see what the lay of the
1751 // land is. If it's mostly SQLITE_NOTADB, then the database should
1752 // be razed.
1753 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1754 if (err != SQLITE_OK)
[email protected]73fb8d52013-07-24 05:04:281755 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err);
[email protected]658f8332010-09-18 04:40:431756
[email protected]2e1cee762013-07-09 14:40:001757#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1758 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1759 // REGEXP support. Add it in dynamically.
1760 err = sqlite3IcuInit(db_);
1761 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1762#endif // OS_IOS && USE_SYSTEM_SQLITE
1763
[email protected]5b96f3772010-09-28 16:30:571764 // If indicated, lock up the database before doing anything else, so
1765 // that the following code doesn't have to deal with locking.
1766 // TODO(shess): This code is brittle. Find the cases where code
1767 // doesn't request |exclusive_locking_| and audit that it does the
1768 // right thing with SQLITE_BUSY, and that it doesn't make
1769 // assumptions about who might change things in the database.
1770 // http://crbug.com/56559
1771 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101772 // TODO(shess): This should probably be a failure. Code which
1773 // requests exclusive locking but doesn't get it is almost certain
1774 // to be ill-tested.
1775 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571776 }
1777
[email protected]4e179ba2012-03-17 16:06:471778 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1779 // DELETE (default) - delete -journal file to commit.
1780 // TRUNCATE - truncate -journal file to commit.
1781 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091782 // TRUNCATE should be faster than DELETE because it won't need directory
1783 // changes for each transaction. PERSIST may break the spirit of using
1784 // secure_delete.
1785 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471786
[email protected]c68ce172011-11-24 22:30:271787 const base::TimeDelta kBusyTimeout =
1788 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1789
[email protected]765b44502009-10-02 05:01:421790 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571791 // Enforce SQLite restrictions on |page_size_|.
1792 DCHECK(!(page_size_ & (page_size_ - 1)))
1793 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241794 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571795 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041796 const std::string sql =
1797 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101798 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421799 }
1800
1801 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041802 const std::string sql =
1803 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101804 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421805 }
1806
[email protected]6e0b1442011-08-09 23:23:581807 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131808 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581809 Close();
[email protected]fed734a2013-07-17 04:45:131810 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1811 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581812 return false;
1813 }
1814
shess5dac334f2015-11-05 20:47:421815 // Set a reasonable chunk size for larger files. This reduces churn from
1816 // remapping memory on size changes. It also reduces filesystem
1817 // fragmentation.
1818 // TODO(shess): It may make sense to have this be hinted by the client.
1819 // Database sizes seem to be bimodal, some clients have consistently small
1820 // databases (<20k) while other clients have a broad distribution of sizes
1821 // (hundreds of kilobytes to many megabytes).
1822 sqlite3_file* file = NULL;
1823 sqlite3_int64 db_size = 0;
1824 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1825 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1826 int chunk_size = 4 * 1024;
1827 if (db_size > 128 * 1024)
1828 chunk_size = 32 * 1024;
1829 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1830 }
1831
shess2f3a814b2015-11-05 18:11:101832 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311833 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1834 // safe range to memory-map based on past regular I/O. This value will be
1835 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1836 // 64-bit platforms.
1837 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1838 std::string mmap_sql =
1839 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1840 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101841
1842 // Determine if memory-mapping has actually been enabled. The Execute() above
1843 // can succeed without changing the amount mapped.
1844 mmap_enabled_ = false;
1845 {
1846 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1847 if (s.Step() && s.ColumnInt64(0) > 0)
1848 mmap_enabled_ = true;
1849 }
1850
[email protected]765b44502009-10-02 05:01:421851 return true;
1852}
1853
[email protected]e5ffd0e42009-09-11 21:30:561854void Connection::DoRollback() {
1855 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321856
1857 // Collect the rollback time manually, sql::Statement would register it as
1858 // query time only.
1859 const base::TimeTicks before = Now();
1860 rollback.RunWithoutTimers();
1861 const base::TimeDelta delta = Now() - before;
1862
1863 RecordUpdateTime(delta);
1864 RecordOneEvent(EVENT_ROLLBACK);
1865
shess7dbd4dee2015-10-06 17:39:161866 // The cache may have been accumulating dirty pages for commit. Note that in
1867 // some cases sql::Transaction can fire rollback after a database is closed.
1868 if (is_open())
1869 ReleaseCacheMemoryIfNeeded(false);
1870
[email protected]44ad7d902012-03-23 00:09:051871 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561872}
1873
1874void Connection::StatementRefCreated(StatementRef* ref) {
1875 DCHECK(open_statements_.find(ref) == open_statements_.end());
1876 open_statements_.insert(ref);
1877}
1878
1879void Connection::StatementRefDeleted(StatementRef* ref) {
1880 StatementRefSet::iterator i = open_statements_.find(ref);
1881 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:591882 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561883 else
1884 open_statements_.erase(i);
1885}
1886
shess58b8df82015-06-03 00:19:321887void Connection::set_histogram_tag(const std::string& tag) {
1888 DCHECK(!is_open());
1889 histogram_tag_ = tag;
1890}
1891
[email protected]210ce0af2013-05-15 09:10:391892void Connection::AddTaggedHistogram(const std::string& name,
1893 size_t sample) const {
1894 if (histogram_tag_.empty())
1895 return;
1896
1897 // TODO(shess): The histogram macros create a bit of static storage
1898 // for caching the histogram object. This code shouldn't execute
1899 // often enough for such caching to be crucial. If it becomes an
1900 // issue, the object could be cached alongside histogram_prefix_.
1901 std::string full_histogram_name = name + "." + histogram_tag_;
1902 base::HistogramBase* histogram =
1903 base::SparseHistogram::FactoryGet(
1904 full_histogram_name,
1905 base::HistogramBase::kUmaTargetedHistogramFlag);
1906 if (histogram)
1907 histogram->Add(sample);
1908}
1909
[email protected]2f496b42013-09-26 18:36:581910int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) {
[email protected]210ce0af2013-05-15 09:10:391911 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
1912 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141913
1914 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581915 if (!sql && stmt)
1916 sql = stmt->GetSQLStatement();
1917 if (!sql)
1918 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061919
1920 std::string id = histogram_tag_;
1921 if (id.empty())
1922 id = DbPath().BaseName().AsUTF8Unsafe();
1923 LOG(ERROR) << id << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141924 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581925 << ": " << GetErrorMessage()
1926 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141927
[email protected]c3881b372013-05-17 08:39:461928 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561929 // Fire from a copy of the callback in case of reentry into
1930 // re/set_error_callback().
1931 // TODO(shess): <http://crbug.com/254584>
1932 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461933 return err;
1934 }
1935
[email protected]faa604e2009-09-25 22:38:591936 // The default handling is to assert on debug and to ignore on release.
[email protected]74cdede2013-09-25 05:39:571937 if (!ShouldIgnoreSqliteError(err))
[email protected]4350e322013-06-18 22:18:101938 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591939 return err;
1940}
1941
[email protected]579446c2013-12-16 18:36:521942bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1943 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1944}
1945
1946bool Connection::QuickIntegrityCheck() {
1947 std::vector<std::string> messages;
1948 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1949 return false;
1950 return messages.size() == 1 && messages[0] == "ok";
1951}
1952
[email protected]80abf152013-05-22 12:42:421953// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521954bool Connection::IntegrityCheckHelper(
1955 const char* pragma_sql,
1956 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421957 messages->clear();
1958
[email protected]4658e2a02013-06-06 23:05:001959 // This has the side effect of setting SQLITE_RecoveryMode, which
1960 // allows SQLite to process through certain cases of corruption.
1961 // Failing to set this pragma probably means that the database is
1962 // beyond recovery.
1963 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1964 if (!Execute(kWritableSchema))
1965 return false;
1966
1967 bool ret = false;
1968 {
[email protected]579446c2013-12-16 18:36:521969 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001970
1971 // The pragma appears to return all results (up to 100 by default)
1972 // as a single string. This doesn't appear to be an API contract,
1973 // it could return separate lines, so loop _and_ split.
1974 while (stmt.Step()) {
1975 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181976 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1977 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001978 }
1979 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421980 }
[email protected]4658e2a02013-06-06 23:05:001981
1982 // Best effort to put things back as they were before.
1983 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1984 ignore_result(Execute(kNoWritableSchema));
1985
1986 return ret;
[email protected]80abf152013-05-22 12:42:421987}
1988
shess58b8df82015-06-03 00:19:321989base::TimeTicks TimeSource::Now() {
1990 return base::TimeTicks::Now();
1991}
1992
[email protected]e5ffd0e42009-09-11 21:30:561993} // namespace sql