blob: 7787adfe28330e4fdadcc8fb4d16eab74b952da9 [file] [log] [blame]
[email protected]64021042012-02-10 20:02:291// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]e5ffd0e42009-09-11 21:30:562// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f0a54b22011-07-19 18:40:215#include "sql/connection.h"
[email protected]e5ffd0e42009-09-11 21:30:566
avi51ba3e692015-12-26 17:30:507#include <limits.h>
avi0b519202015-12-21 07:25:198#include <stddef.h>
9#include <stdint.h>
[email protected]e5ffd0e42009-09-11 21:30:5610#include <string.h>
dchenge48600452015-12-28 02:24:5011#include <utility>
[email protected]e5ffd0e42009-09-11 21:30:5612
shessc9e80ae22015-08-12 21:39:1113#include "base/bind.h"
shessc8cd2a162015-10-22 20:30:4614#include "base/debug/dump_without_crashing.h"
[email protected]57999812013-02-24 05:40:5215#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4416#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4617#include "base/format_macros.h"
18#include "base/json/json_file_value_serializer.h"
[email protected]a7ec1292013-07-22 22:02:1819#include "base/lazy_instance.h"
[email protected]e5ffd0e42009-09-11 21:30:5620#include "base/logging.h"
shessc9e80ae22015-08-12 21:39:1121#include "base/message_loop/message_loop.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5022#include "base/metrics/histogram.h"
[email protected]210ce0af2013-05-15 09:10:3923#include "base/metrics/sparse_histogram.h"
[email protected]80abf152013-05-22 12:42:4224#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1925#include "base/strings/string_util.h"
26#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4527#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1828#include "base/synchronization/lock.h"
ssid9f8022f2015-10-12 17:49:0329#include "base/trace_event/memory_dump_manager.h"
ssid3be5b1ec2016-01-13 14:21:5730#include "sql/connection_memory_dump_provider.h"
shess9bf2c672015-12-18 01:18:0831#include "sql/meta_table.h"
[email protected]f0a54b22011-07-19 18:40:2132#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0333#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5634
[email protected]2e1cee762013-07-09 14:40:0035#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
36#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
37#endif
38
[email protected]5b96f3772010-09-28 16:30:5739namespace {
40
41// Spin for up to a second waiting for the lock to clear when setting
42// up the database.
43// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2744const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5745
vichang7ce37c12016-01-28 22:09:0346bool g_mmap_disabled_default = false;
47
[email protected]5b96f3772010-09-28 16:30:5748class ScopedBusyTimeout {
49 public:
50 explicit ScopedBusyTimeout(sqlite3* db)
51 : db_(db) {
52 }
53 ~ScopedBusyTimeout() {
54 sqlite3_busy_timeout(db_, 0);
55 }
56
57 int SetTimeout(base::TimeDelta timeout) {
58 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
59 return sqlite3_busy_timeout(db_,
60 static_cast<int>(timeout.InMilliseconds()));
61 }
62
63 private:
64 sqlite3* db_;
65};
66
[email protected]6d42f152012-11-10 00:38:2467// Helper to "safely" enable writable_schema. No error checking
68// because it is reasonable to just forge ahead in case of an error.
69// If turning it on fails, then most likely nothing will work, whereas
70// if turning it off fails, it only matters if some code attempts to
71// continue working with the database and tries to modify the
72// sqlite_master table (none of our code does this).
73class ScopedWritableSchema {
74 public:
75 explicit ScopedWritableSchema(sqlite3* db)
76 : db_(db) {
77 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
78 }
79 ~ScopedWritableSchema() {
80 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
81 }
82
83 private:
84 sqlite3* db_;
85};
86
[email protected]7bae5742013-07-10 20:46:1687// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
88// SQLite error code from running the backup step.
89int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
90 DCHECK_NE(src, dst);
91 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
92 if (!backup) {
93 // Since this call only sets things up, this indicates a gross
94 // error in SQLite.
95 DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
96 return sqlite3_errcode(dst);
97 }
98
99 // -1 backs up the entire database.
100 int rc = sqlite3_backup_step(backup, -1);
101 int pages = sqlite3_backup_pagecount(backup);
102 sqlite3_backup_finish(backup);
103
104 // If successful, exactly one page should have been backed up. If
105 // this breaks, check this function to make sure assumptions aren't
106 // being broken.
107 if (rc == SQLITE_DONE)
108 DCHECK_EQ(pages, 1);
109
110 return rc;
111}
112
[email protected]8d409412013-07-19 18:25:30113// Be very strict on attachment point. SQLite can handle a much wider
114// character set with appropriate quoting, but Chromium code should
115// just use clean names to start with.
116bool ValidAttachmentPoint(const char* attachment_point) {
117 for (size_t i = 0; attachment_point[i]; ++i) {
118 if (!((attachment_point[i] >= '0' && attachment_point[i] <= '9') ||
119 (attachment_point[i] >= 'a' && attachment_point[i] <= 'z') ||
120 (attachment_point[i] >= 'A' && attachment_point[i] <= 'Z') ||
121 attachment_point[i] == '_')) {
122 return false;
123 }
124 }
125 return true;
126}
127
shessc9e80ae22015-08-12 21:39:11128void RecordSqliteMemory10Min() {
avi0b519202015-12-21 07:25:19129 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11130 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.TenMinutes", used / 1024);
131}
132
133void RecordSqliteMemoryHour() {
avi0b519202015-12-21 07:25:19134 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11135 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneHour", used / 1024);
136}
137
138void RecordSqliteMemoryDay() {
avi0b519202015-12-21 07:25:19139 const int64_t used = sqlite3_memory_used();
shessc9e80ae22015-08-12 21:39:11140 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneDay", used / 1024);
141}
142
shess2d48e942015-08-25 17:39:51143void RecordSqliteMemoryWeek() {
avi0b519202015-12-21 07:25:19144 const int64_t used = sqlite3_memory_used();
shess2d48e942015-08-25 17:39:51145 UMA_HISTOGRAM_COUNTS("Sqlite.MemoryKB.OneWeek", used / 1024);
146}
147
[email protected]a7ec1292013-07-22 22:02:18148// SQLite automatically calls sqlite3_initialize() lazily, but
149// sqlite3_initialize() uses double-checked locking and thus can have
150// data races.
151//
152// TODO(shess): Another alternative would be to have
153// sqlite3_initialize() called as part of process bring-up. If this
154// is changed, remove the dynamic_annotations dependency in sql.gyp.
155base::LazyInstance<base::Lock>::Leaky
156 g_sqlite_init_lock = LAZY_INSTANCE_INITIALIZER;
157void InitializeSqlite() {
158 base::AutoLock lock(g_sqlite_init_lock.Get());
shessc9e80ae22015-08-12 21:39:11159 static bool first_call = true;
160 if (first_call) {
161 sqlite3_initialize();
162
163 // Schedule callback to record memory footprint histograms at 10m, 1h, and
164 // 1d. There may not be a message loop in tests.
165 if (base::MessageLoop::current()) {
166 base::MessageLoop::current()->PostDelayedTask(
167 FROM_HERE, base::Bind(&RecordSqliteMemory10Min),
168 base::TimeDelta::FromMinutes(10));
169 base::MessageLoop::current()->PostDelayedTask(
170 FROM_HERE, base::Bind(&RecordSqliteMemoryHour),
171 base::TimeDelta::FromHours(1));
172 base::MessageLoop::current()->PostDelayedTask(
173 FROM_HERE, base::Bind(&RecordSqliteMemoryDay),
174 base::TimeDelta::FromDays(1));
shess2d48e942015-08-25 17:39:51175 base::MessageLoop::current()->PostDelayedTask(
176 FROM_HERE, base::Bind(&RecordSqliteMemoryWeek),
177 base::TimeDelta::FromDays(7));
shessc9e80ae22015-08-12 21:39:11178 }
179
180 first_call = false;
181 }
[email protected]a7ec1292013-07-22 22:02:18182}
183
[email protected]8ada10f2013-12-21 00:42:34184// Helper to get the sqlite3_file* associated with the "main" database.
185int GetSqlite3File(sqlite3* db, sqlite3_file** file) {
186 *file = NULL;
187 int rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_FILE_POINTER, file);
188 if (rc != SQLITE_OK)
189 return rc;
190
191 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
192 // content_unittests, even though it should not be possible.
193 // http://crbug.com/329982
194 if (!*file || !(*file)->pMethods)
195 return SQLITE_ERROR;
196
197 return rc;
198}
199
shess5dac334f2015-11-05 20:47:42200// Convenience to get the sqlite3_file* and the size for the "main" database.
201int GetSqlite3FileAndSize(sqlite3* db,
202 sqlite3_file** file, sqlite3_int64* db_size) {
203 int rc = GetSqlite3File(db, file);
204 if (rc != SQLITE_OK)
205 return rc;
206
207 return (*file)->pMethods->xFileSize(*file, db_size);
208}
209
shess58b8df82015-06-03 00:19:32210// This should match UMA_HISTOGRAM_MEDIUM_TIMES().
211base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
212 return base::Histogram::FactoryTimeGet(
213 name,
214 base::TimeDelta::FromMilliseconds(10),
215 base::TimeDelta::FromMinutes(3),
216 50,
217 base::HistogramBase::kUmaTargetedHistogramFlag);
218}
219
erg102ceb412015-06-20 01:38:13220std::string AsUTF8ForSQL(const base::FilePath& path) {
221#if defined(OS_WIN)
222 return base::WideToUTF8(path.value());
223#elif defined(OS_POSIX)
224 return path.value();
225#endif
226}
227
[email protected]5b96f3772010-09-28 16:30:57228} // namespace
229
[email protected]e5ffd0e42009-09-11 21:30:56230namespace sql {
231
[email protected]4350e322013-06-18 22:18:10232// static
233Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL;
234
235// static
[email protected]74cdede2013-09-25 05:39:57236bool Connection::ShouldIgnoreSqliteError(int error) {
[email protected]4350e322013-06-18 22:18:10237 if (!current_ignorer_cb_)
238 return false;
239 return current_ignorer_cb_->Run(error);
240}
241
shessf7e988f2015-11-13 00:41:06242// static
243bool Connection::ShouldIgnoreSqliteCompileError(int error) {
244 // Put this first in case tests need to see that the check happened.
245 if (ShouldIgnoreSqliteError(error))
246 return true;
247
248 // Trim extended error codes.
249 int basic_error = error & 0xff;
250
251 // These errors relate more to the runtime context of the system than to
252 // errors with a SQL statement or with the schema, so they aren't generally
253 // interesting to flag. This list is not comprehensive.
254 return basic_error == SQLITE_BUSY ||
255 basic_error == SQLITE_NOTADB ||
256 basic_error == SQLITE_CORRUPT;
257}
258
vichang7ce37c12016-01-28 22:09:03259// static
260void Connection::set_mmap_disabled_by_default() {
261 g_mmap_disabled_default = true;
262}
263
264
shessc8cd2a162015-10-22 20:30:46265void Connection::ReportDiagnosticInfo(int extended_error, Statement* stmt) {
266 AssertIOAllowed();
267
268 std::string debug_info;
269 const int error = (extended_error & 0xFF);
270 if (error == SQLITE_CORRUPT) {
shess874ea1bd2016-02-02 05:15:06271 // CollectCorruptionInfo() is implemented in terms of sql::Connection,
272 // prevent reentrant calls to the error callback.
273 // TODO(shess): Rewrite IntegrityCheckHelper() in terms of raw SQLite.
274 ErrorCallback original_callback = std::move(error_callback_);
275 reset_error_callback();
276
shessc8cd2a162015-10-22 20:30:46277 debug_info = CollectCorruptionInfo();
shess874ea1bd2016-02-02 05:15:06278
279 error_callback_ = std::move(original_callback);
shessc8cd2a162015-10-22 20:30:46280 } else {
281 debug_info = CollectErrorInfo(extended_error, stmt);
282 }
283
284 if (!debug_info.empty() && RegisterIntentToUpload()) {
285 char debug_buf[2000];
286 base::strlcpy(debug_buf, debug_info.c_str(), arraysize(debug_buf));
287 base::debug::Alias(&debug_buf);
288
289 base::debug::DumpWithoutCrashing();
290 }
291}
292
[email protected]4350e322013-06-18 22:18:10293// static
294void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
295 CHECK(current_ignorer_cb_ == NULL);
296 current_ignorer_cb_ = cb;
297}
298
299// static
300void Connection::ResetErrorIgnorer() {
301 CHECK(current_ignorer_cb_);
302 current_ignorer_cb_ = NULL;
303}
304
[email protected]e5ffd0e42009-09-11 21:30:56305bool StatementID::operator<(const StatementID& other) const {
306 if (number_ != other.number_)
307 return number_ < other.number_;
308 return strcmp(str_, other.str_) < 0;
309}
310
[email protected]e5ffd0e42009-09-11 21:30:56311Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38312 sqlite3_stmt* stmt,
313 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56314 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38315 stmt_(stmt),
316 was_valid_(was_valid) {
317 if (connection)
318 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56319}
320
321Connection::StatementRef::~StatementRef() {
322 if (connection_)
323 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38324 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56325}
326
[email protected]41a97c812013-02-07 02:35:38327void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56328 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50329 // Call to AssertIOAllowed() cannot go at the beginning of the function
330 // because Close() is called unconditionally from destructor to clean
331 // connection_. And if this is inactive statement this won't cause any
332 // disk access and destructor most probably will be called on thread
333 // not allowing disk access.
334 // TODO([email protected]): This should move to the beginning
335 // of the function. http://crbug.com/136655.
336 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56337 sqlite3_finalize(stmt_);
338 stmt_ = NULL;
339 }
340 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38341
342 // Forced close is expected to happen from a statement error
343 // handler. In that case maintain the sense of |was_valid_| which
344 // previously held for this ref.
345 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56346}
347
348Connection::Connection()
349 : db_(NULL),
350 page_size_(0),
351 cache_size_(0),
352 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36353 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56354 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50355 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16356 in_memory_(false),
shess58b8df82015-06-03 00:19:32357 poisoned_(false),
vichang7ce37c12016-01-28 22:09:03358 mmap_disabled_(g_mmap_disabled_default),
shess7dbd4dee2015-10-06 17:39:16359 mmap_enabled_(false),
360 total_changes_at_last_release_(0),
shess58b8df82015-06-03 00:19:32361 stats_histogram_(NULL),
362 commit_time_histogram_(NULL),
363 autocommit_time_histogram_(NULL),
364 update_time_histogram_(NULL),
365 query_time_histogram_(NULL),
366 clock_(new TimeSource()) {
[email protected]526b4662013-06-14 04:09:12367}
[email protected]e5ffd0e42009-09-11 21:30:56368
369Connection::~Connection() {
370 Close();
371}
372
shess58b8df82015-06-03 00:19:32373void Connection::RecordEvent(Events event, size_t count) {
374 for (size_t i = 0; i < count; ++i) {
375 UMA_HISTOGRAM_ENUMERATION("Sqlite.Stats", event, EVENT_MAX_VALUE);
376 }
377
378 if (stats_histogram_) {
379 for (size_t i = 0; i < count; ++i) {
380 stats_histogram_->Add(event);
381 }
382 }
383}
384
385void Connection::RecordCommitTime(const base::TimeDelta& delta) {
386 RecordUpdateTime(delta);
387 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.CommitTime", delta);
388 if (commit_time_histogram_)
389 commit_time_histogram_->AddTime(delta);
390}
391
392void Connection::RecordAutoCommitTime(const base::TimeDelta& delta) {
393 RecordUpdateTime(delta);
394 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.AutoCommitTime", delta);
395 if (autocommit_time_histogram_)
396 autocommit_time_histogram_->AddTime(delta);
397}
398
399void Connection::RecordUpdateTime(const base::TimeDelta& delta) {
400 RecordQueryTime(delta);
401 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.UpdateTime", delta);
402 if (update_time_histogram_)
403 update_time_histogram_->AddTime(delta);
404}
405
406void Connection::RecordQueryTime(const base::TimeDelta& delta) {
407 UMA_HISTOGRAM_MEDIUM_TIMES("Sqlite.QueryTime", delta);
408 if (query_time_histogram_)
409 query_time_histogram_->AddTime(delta);
410}
411
412void Connection::RecordTimeAndChanges(
413 const base::TimeDelta& delta, bool read_only) {
414 if (read_only) {
415 RecordQueryTime(delta);
416 } else {
417 const int changes = sqlite3_changes(db_);
418 if (sqlite3_get_autocommit(db_)) {
419 RecordAutoCommitTime(delta);
420 RecordEvent(EVENT_CHANGES_AUTOCOMMIT, changes);
421 } else {
422 RecordUpdateTime(delta);
423 RecordEvent(EVENT_CHANGES, changes);
424 }
425 }
426}
427
[email protected]a3ef4832013-02-02 05:12:33428bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02429 if (!histogram_tag_.empty()) {
tfarina720d4f32015-05-11 22:31:26430 int64_t size_64 = 0;
[email protected]56285702013-12-04 18:22:49431 if (base::GetFileSize(path, &size_64)) {
[email protected]348ac8f52013-05-21 03:27:02432 size_t sample = static_cast<size_t>(size_64 / 1024);
433 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
434 base::HistogramBase* histogram =
435 base::Histogram::FactoryGet(
436 full_histogram_name, 1, 1000000, 50,
437 base::HistogramBase::kUmaTargetedHistogramFlag);
438 if (histogram)
439 histogram->Add(sample);
shess9bf2c672015-12-18 01:18:08440 UMA_HISTOGRAM_COUNTS("Sqlite.SizeKB", sample);
[email protected]348ac8f52013-05-21 03:27:02441 }
442 }
443
erg102ceb412015-06-20 01:38:13444 return OpenInternal(AsUTF8ForSQL(path), RETRY_ON_POISON);
[email protected]765b44502009-10-02 05:01:42445}
[email protected]e5ffd0e42009-09-11 21:30:56446
[email protected]765b44502009-10-02 05:01:42447bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50448 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13449 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56450}
451
[email protected]8d409412013-07-19 18:25:30452bool Connection::OpenTemporary() {
453 return OpenInternal("", NO_RETRY);
454}
455
[email protected]41a97c812013-02-07 02:35:38456void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47457 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
458 // will delete the -journal file. For ChromiumOS or other more
459 // embedded systems, this is probably not appropriate, whereas on
460 // desktop it might make some sense.
461
[email protected]4b350052012-02-24 20:40:48462 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48463
[email protected]41a97c812013-02-07 02:35:38464 // Release cached statements.
465 statement_cache_.clear();
466
467 // With cached statements released, in-use statements will remain.
468 // Closing the database while statements are in use is an API
469 // violation, except for forced close (which happens from within a
470 // statement's error handler).
471 DCHECK(forced || open_statements_.empty());
472
473 // Deactivate any outstanding statements so sqlite3_close() works.
474 for (StatementRefSet::iterator i = open_statements_.begin();
475 i != open_statements_.end(); ++i)
476 (*i)->Close(forced);
477 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48478
[email protected]e5ffd0e42009-09-11 21:30:56479 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50480 // Call to AssertIOAllowed() cannot go at the beginning of the function
481 // because Close() must be called from destructor to clean
482 // statement_cache_, it won't cause any disk access and it most probably
483 // will happen on thread not allowing disk access.
484 // TODO([email protected]): This should move to the beginning
485 // of the function. http://crbug.com/136655.
486 AssertIOAllowed();
[email protected]73fb8d52013-07-24 05:04:28487
ssid3be5b1ec2016-01-13 14:21:57488 // Reseting acquires a lock to ensure no dump is happening on the database
489 // at the same time. Unregister takes ownership of provider and it is safe
490 // since the db is reset. memory_dump_provider_ could be null if db_ was
491 // poisoned.
492 if (memory_dump_provider_) {
493 memory_dump_provider_->ResetDatabase();
494 base::trace_event::MemoryDumpManager::GetInstance()
495 ->UnregisterAndDeleteDumpProviderSoon(
496 std::move(memory_dump_provider_));
497 }
498
[email protected]73fb8d52013-07-24 05:04:28499 int rc = sqlite3_close(db_);
500 if (rc != SQLITE_OK) {
501 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.CloseFailure", rc);
502 DLOG(FATAL) << "sqlite3_close failed: " << GetErrorMessage();
503 }
[email protected]e5ffd0e42009-09-11 21:30:56504 }
[email protected]fed734a2013-07-17 04:45:13505 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56506}
507
[email protected]41a97c812013-02-07 02:35:38508void Connection::Close() {
509 // If the database was already closed by RazeAndClose(), then no
510 // need to close again. Clear the |poisoned_| bit so that incorrect
511 // API calls are caught.
512 if (poisoned_) {
513 poisoned_ = false;
514 return;
515 }
516
517 CloseInternal(false);
518}
519
[email protected]e5ffd0e42009-09-11 21:30:56520void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50521 AssertIOAllowed();
522
[email protected]e5ffd0e42009-09-11 21:30:56523 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38524 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56525 return;
526 }
527
[email protected]8ada10f2013-12-21 00:42:34528 // Use local settings if provided, otherwise use documented defaults. The
529 // actual results could be fetching via PRAGMA calls.
530 const int page_size = page_size_ ? page_size_ : 1024;
531 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
532 if (preload_size < 1)
[email protected]e5ffd0e42009-09-11 21:30:56533 return;
534
[email protected]8ada10f2013-12-21 00:42:34535 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:34536 sqlite3_int64 file_size = 0;
shess5dac334f2015-11-05 20:47:42537 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
[email protected]8ada10f2013-12-21 00:42:34538 if (rc != SQLITE_OK)
539 return;
540
541 // Don't preload more than the file contains.
542 if (preload_size > file_size)
543 preload_size = file_size;
544
545 scoped_ptr<char[]> buf(new char[page_size]);
shessde60c5f12015-04-21 17:34:46546 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
[email protected]8ada10f2013-12-21 00:42:34547 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
shessd90aeea82015-11-13 02:24:31548
549 // TODO(shess): Consider calling OnSqliteError().
[email protected]8ada10f2013-12-21 00:42:34550 if (rc != SQLITE_OK)
551 return;
552 }
[email protected]e5ffd0e42009-09-11 21:30:56553}
554
shess7dbd4dee2015-10-06 17:39:16555// SQLite keeps unused pages associated with a connection in a cache. It asks
556// the cache for pages by an id, and if the page is present and the database is
557// unchanged, it considers the content of the page valid and doesn't read it
558// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
559// structures created from the memory map data before consulting the cache. On
560// write SQLite creates a new in-memory page structure, copies the data from the
561// memory map, and later writes it, releasing the updated page back to the
562// cache.
563//
564// This means that in memory-mapped mode, the contents of the cached pages are
565// not re-used for reads, but they are re-used for writes if the re-written page
566// is still in the cache. The implementation of sqlite3_db_release_memory() as
567// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
568// connection, so it should free these pages.
569//
570// Unfortunately, the zero page is also freed. That page is never accessed
571// using memory-mapped I/O, and the cached copy can be re-used after verifying
572// the file change counter on disk. Also, fresh pages from cache receive some
573// pager-level initialization before they can be used. Since the information
574// involved will immediately be accessed in various ways, it is unclear if the
575// additional overhead is material, or just moving processor cache effects
576// around.
577//
578// TODO(shess): It would be better to release the pages immediately when they
579// are no longer needed. This would basically happen after SQLite commits a
580// transaction. I had implemented a pcache wrapper to do this, but it involved
581// layering violations, and it had to be setup before any other sqlite call,
582// which was brittle. Also, for large files it would actually make sense to
583// maintain the existing pcache behavior for blocks past the memory-mapped
584// segment. I think drh would accept a reasonable implementation of the overall
585// concept for upstreaming to SQLite core.
586//
587// TODO(shess): Another possibility would be to set the cache size small, which
588// would keep the zero page around, plus some pre-initialized pages, and SQLite
589// can manage things. The downside is that updates larger than the cache would
590// spill to the journal. That could be compensated by setting cache_spill to
591// false. The downside then is that it allows open-ended use of memory for
592// large transactions.
593//
594// TODO(shess): The TrimMemory() trick of bouncing the cache size would also
595// work. There could be two prepared statements, one for cache_size=1 one for
596// cache_size=goal.
597void Connection::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
shess644fc8a2016-02-26 18:15:58598 // The database could have been closed during a transaction as part of error
599 // recovery.
600 if (!db_) {
601 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
602 return;
603 }
shess7dbd4dee2015-10-06 17:39:16604
605 // If memory-mapping is not enabled, the page cache helps performance.
606 if (!mmap_enabled_)
607 return;
608
609 // On caller request, force the change comparison to fail. Done before the
610 // transaction-nesting test so that the signal can carry to transaction
611 // commit.
612 if (implicit_change_performed)
613 --total_changes_at_last_release_;
614
615 // Cached pages may be re-used within the same transaction.
616 if (transaction_nesting())
617 return;
618
619 // If no changes have been made, skip flushing. This allows the first page of
620 // the database to remain in cache across multiple reads.
621 const int total_changes = sqlite3_total_changes(db_);
622 if (total_changes == total_changes_at_last_release_)
623 return;
624
625 total_changes_at_last_release_ = total_changes;
626 sqlite3_db_release_memory(db_);
627}
628
shessc8cd2a162015-10-22 20:30:46629base::FilePath Connection::DbPath() const {
630 if (!is_open())
631 return base::FilePath();
632
633 const char* path = sqlite3_db_filename(db_, "main");
634 const base::StringPiece db_path(path);
635#if defined(OS_WIN)
636 return base::FilePath(base::UTF8ToWide(db_path));
637#elif defined(OS_POSIX)
638 return base::FilePath(db_path);
639#else
640 NOTREACHED();
641 return base::FilePath();
642#endif
643}
644
645// Data is persisted in a file shared between databases in the same directory.
646// The "sqlite-diag" file contains a dictionary with the version number, and an
647// array of histogram tags for databases which have been dumped.
648bool Connection::RegisterIntentToUpload() const {
649 static const char* kVersionKey = "version";
650 static const char* kDiagnosticDumpsKey = "DiagnosticDumps";
651 static int kVersion = 1;
652
653 AssertIOAllowed();
654
655 if (histogram_tag_.empty())
656 return false;
657
658 if (!is_open())
659 return false;
660
661 if (in_memory_)
662 return false;
663
664 const base::FilePath db_path = DbPath();
665 if (db_path.empty())
666 return false;
667
668 // Put the collection of diagnostic data next to the databases. In most
669 // cases, this is the profile directory, but safe-browsing stores a Cookies
670 // file in the directory above the profile directory.
671 base::FilePath breadcrumb_path(
672 db_path.DirName().Append(FILE_PATH_LITERAL("sqlite-diag")));
673
674 // Lock against multiple updates to the diagnostics file. This code should
675 // seldom be called in the first place, and when called it should seldom be
676 // called for multiple databases, and when called for multiple databases there
677 // is _probably_ something systemic wrong with the user's system. So the lock
678 // should never be contended, but when it is the database experience is
679 // already bad.
680 base::AutoLock lock(g_sqlite_init_lock.Get());
681
682 scoped_ptr<base::Value> root;
683 if (!base::PathExists(breadcrumb_path)) {
684 scoped_ptr<base::DictionaryValue> root_dict(new base::DictionaryValue());
685 root_dict->SetInteger(kVersionKey, kVersion);
686
687 scoped_ptr<base::ListValue> dumps(new base::ListValue);
688 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50689 root_dict->Set(kDiagnosticDumpsKey, std::move(dumps));
shessc8cd2a162015-10-22 20:30:46690
dchenge48600452015-12-28 02:24:50691 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46692 } else {
693 // Failure to read a valid dictionary implies that something is going wrong
694 // on the system.
695 JSONFileValueDeserializer deserializer(breadcrumb_path);
696 scoped_ptr<base::Value> read_root(
697 deserializer.Deserialize(nullptr, nullptr));
698 if (!read_root.get())
699 return false;
700 scoped_ptr<base::DictionaryValue> root_dict =
dchenge48600452015-12-28 02:24:50701 base::DictionaryValue::From(std::move(read_root));
shessc8cd2a162015-10-22 20:30:46702 if (!root_dict)
703 return false;
704
705 // Don't upload if the version is missing or newer.
706 int version = 0;
707 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
708 return false;
709
710 base::ListValue* dumps = nullptr;
711 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
712 return false;
713
714 const size_t size = dumps->GetSize();
715 for (size_t i = 0; i < size; ++i) {
716 std::string s;
717
718 // Don't upload if the value isn't a string, or indicates a prior upload.
719 if (!dumps->GetString(i, &s) || s == histogram_tag_)
720 return false;
721 }
722
723 // Record intention to proceed with upload.
724 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50725 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46726 }
727
728 const base::FilePath breadcrumb_new =
729 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
730 base::DeleteFile(breadcrumb_new, false);
731
732 // No upload if the breadcrumb file cannot be updated.
733 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
734 // the data on disk. For now, losing the data is not a big problem, so the
735 // sync overhead would probably not be worth it.
736 JSONFileValueSerializer serializer(breadcrumb_new);
737 if (!serializer.Serialize(*root))
738 return false;
739 if (!base::PathExists(breadcrumb_new))
740 return false;
741 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
742 base::DeleteFile(breadcrumb_new, false);
743 return false;
744 }
745
746 return true;
747}
748
749std::string Connection::CollectErrorInfo(int error, Statement* stmt) const {
750 // Buffer for accumulating debugging info about the error. Place
751 // more-relevant information earlier, in case things overflow the
752 // fixed-size reporting buffer.
753 std::string debug_info;
754
755 // The error message from the failed operation.
756 base::StringAppendF(&debug_info, "db error: %d/%s\n",
757 GetErrorCode(), GetErrorMessage());
758
759 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
760 // reading code does not entirely convince me. Remove if they turn out to be
761 // the same.
762 if (error != GetErrorCode())
763 base::StringAppendF(&debug_info, "reported error: %d\n", error);
764
765 // System error information. Interpretation of Windows errors is different
766 // from posix.
767#if defined(OS_WIN)
768 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
769#elif defined(OS_POSIX)
770 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
771#else
772 NOTREACHED(); // Add appropriate log info.
773#endif
774
775 if (stmt) {
776 base::StringAppendF(&debug_info, "statement: %s\n",
777 stmt->GetSQLStatement());
778 } else {
779 base::StringAppendF(&debug_info, "statement: NULL\n");
780 }
781
782 // SQLITE_ERROR often indicates some sort of mismatch between the statement
783 // and the schema, possibly due to a failed schema migration.
784 if (error == SQLITE_ERROR) {
785 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
786 sqlite3_stmt* s;
787 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
788 if (rc == SQLITE_OK) {
789 rc = sqlite3_step(s);
790 if (rc == SQLITE_ROW) {
791 base::StringAppendF(&debug_info, "version: %d\n",
792 sqlite3_column_int(s, 0));
793 } else if (rc == SQLITE_DONE) {
794 debug_info += "version: none\n";
795 } else {
796 base::StringAppendF(&debug_info, "version: error %d\n", rc);
797 }
798 sqlite3_finalize(s);
799 } else {
800 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
801 }
802
803 debug_info += "schema:\n";
804
805 // sqlite_master has columns:
806 // type - "index" or "table".
807 // name - name of created element.
808 // tbl_name - name of element, or target table in case of index.
809 // rootpage - root page of the element in database file.
810 // sql - SQL to create the element.
811 // In general, the |sql| column is sufficient to derive the other columns.
812 // |rootpage| is not interesting for debugging, without the contents of the
813 // database. The COALESCE is because certain automatic elements will have a
814 // |name| but no |sql|,
815 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
816 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
817 if (rc == SQLITE_OK) {
818 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
819 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
820 }
821 if (rc != SQLITE_DONE)
822 base::StringAppendF(&debug_info, "error %d\n", rc);
823 sqlite3_finalize(s);
824 } else {
825 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
826 }
827 }
828
829 return debug_info;
830}
831
832// TODO(shess): Since this is only called in an error situation, it might be
833// prudent to rewrite in terms of SQLite API calls, and mark the function const.
834std::string Connection::CollectCorruptionInfo() {
835 AssertIOAllowed();
836
837 // If the file cannot be accessed it is unlikely that an integrity check will
838 // turn up actionable information.
839 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19840 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46841 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
842 return std::string();
843
844 // Buffer for accumulating debugging info about the error. Place
845 // more-relevant information earlier, in case things overflow the
846 // fixed-size reporting buffer.
847 std::string debug_info;
848 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
849 db_size);
850
851 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19852 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46853 if (db_size > kMaxIntegrityCheckSize) {
854 debug_info += "integrity_check skipped due to size\n";
855 } else {
856 std::vector<std::string> messages;
857
858 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
859 // into a string. Probably should be refactored.
860 const base::TimeTicks before = base::TimeTicks::Now();
861 FullIntegrityCheck(&messages);
862 base::StringAppendF(
863 &debug_info,
864 "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
865 (base::TimeTicks::Now() - before).InMilliseconds(),
866 messages.size());
867
868 // SQLite returns up to 100 messages by default, trim deeper to
869 // keep close to the 2000-character size limit for dumping.
870 const size_t kMaxMessages = 20;
871 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
872 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
873 }
874 }
875
876 return debug_info;
877}
878
shessd90aeea82015-11-13 02:24:31879size_t Connection::GetAppropriateMmapSize() {
880 AssertIOAllowed();
881
shessd90aeea82015-11-13 02:24:31882#if defined(OS_IOS)
883 // iOS SQLite does not support memory mapping.
884 return 0;
885#endif
886
shess9bf2c672015-12-18 01:18:08887 // How much to map if no errors are found. 50MB encompasses the 99th
888 // percentile of Chrome databases in the wild, so this should be good.
889 const size_t kMmapEverything = 256 * 1024 * 1024;
890
891 // If the database doesn't have a place to track progress, assume the best.
892 // This will happen when new databases are created, or if a database doesn't
893 // use a meta table. sql::MetaTable::Init() will preload kMmapSuccess.
894 // TODO(shess): Databases not using meta include:
895 // DOMStorageDatabase (localstorage)
896 // ActivityDatabase (extensions activity log)
897 // PredictorDatabase (prefetch and autocomplete predictor data)
898 // SyncDirectory (sync metadata storage)
899 // For now, these all have mmap disabled to allow other databases to get the
900 // default-enable path. sqlite-diag could be an alternative for all but
901 // DOMStorageDatabase, which creates many small databases.
902 // http://crbug.com/537742
903 if (!MetaTable::DoesTableExist(this)) {
shessd90aeea82015-11-13 02:24:31904 RecordOneEvent(EVENT_MMAP_META_MISSING);
shess9bf2c672015-12-18 01:18:08905 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31906 }
907
shess9bf2c672015-12-18 01:18:08908 int64_t mmap_ofs = 0;
909 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
910 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
911 return 0;
shessd90aeea82015-11-13 02:24:31912 }
913
914 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08915 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31916 RecordOneEvent(EVENT_MMAP_FAILED);
917 return 0;
shess9bf2c672015-12-18 01:18:08918 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31919 // Continue reading from previous offset.
920 DCHECK_GE(mmap_ofs, 0);
921
922 // TODO(shess): Could this reading code be shared with Preload()? It would
923 // require locking twice (this code wouldn't be able to access |db_size| so
924 // the helper would have to return amount read).
925
926 // Read more of the database looking for errors. The VFS interface is used
927 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
928 // to limit checking to 20MB per run of Chromium.
929 sqlite3_file* file = NULL;
930 sqlite3_int64 db_size = 0;
931 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
932 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
933 return 0;
934 }
935
936 // Read the data left, or |g_reads_allowed|, whichever is smaller.
937 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
938 // in a single Chromium run.
939 sqlite3_int64 amount = db_size - mmap_ofs;
940 if (amount < 0)
941 amount = 0;
942 if (amount > 0) {
943 base::AutoLock lock(g_sqlite_init_lock.Get());
944 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
945 if (g_reads_allowed < amount)
946 amount = g_reads_allowed;
947 g_reads_allowed -= amount;
948 }
949
950 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
951 // database was truncated after a previous pass.
952 if (amount <= 0 && mmap_ofs < db_size) {
953 DCHECK_EQ(0, amount);
954 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
955 } else {
956 static const int kPageSize = 4096;
957 char buf[kPageSize];
958 while (amount > 0) {
959 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
960 if (rc == SQLITE_OK) {
961 mmap_ofs += sizeof(buf);
962 amount -= sizeof(buf);
963 } else if (rc == SQLITE_IOERR_SHORT_READ) {
964 // Reached EOF for a database with page size < |kPageSize|.
965 mmap_ofs = db_size;
966 break;
967 } else {
968 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08969 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31970 break;
971 }
972 }
973
974 // Log these events after update to distinguish meta update failure.
975 Events event;
976 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08977 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31978 event = EVENT_MMAP_SUCCESS_NEW;
979 } else if (mmap_ofs > 0) {
980 event = EVENT_MMAP_SUCCESS_PARTIAL;
981 } else {
shess9bf2c672015-12-18 01:18:08982 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31983 event = EVENT_MMAP_FAILED_NEW;
984 }
985
shess9bf2c672015-12-18 01:18:08986 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
shessd90aeea82015-11-13 02:24:31987 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
988 return 0;
989 }
990
991 RecordOneEvent(event);
992 }
993 }
994
shess9bf2c672015-12-18 01:18:08995 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:31996 return 0;
shess9bf2c672015-12-18 01:18:08997 if (mmap_ofs == MetaTable::kMmapSuccess)
998 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31999 return mmap_ofs;
1000}
1001
[email protected]be7995f12013-07-18 18:49:141002void Connection::TrimMemory(bool aggressively) {
1003 if (!db_)
1004 return;
1005
1006 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
1007 int original_cache_size;
1008 {
1009 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
1010 if (!sql_get_original.Step()) {
1011 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
1012 return;
1013 }
1014 original_cache_size = sql_get_original.ColumnInt(0);
1015 }
1016 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
1017
1018 // Force sqlite to try to reduce page cache usage.
1019 const std::string sql_shrink =
1020 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
1021 if (!Execute(sql_shrink.c_str()))
1022 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
1023
1024 // Restore cache size.
1025 const std::string sql_restore =
1026 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
1027 if (!Execute(sql_restore.c_str()))
1028 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
1029}
1030
[email protected]8e0c01282012-04-06 19:36:491031// Create an in-memory database with the existing database's page
1032// size, then backup that database over the existing database.
1033bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:501034 AssertIOAllowed();
1035
[email protected]8e0c01282012-04-06 19:36:491036 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381037 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491038 return false;
1039 }
1040
1041 if (transaction_nesting_ > 0) {
1042 DLOG(FATAL) << "Cannot raze within a transaction";
1043 return false;
1044 }
1045
1046 sql::Connection null_db;
1047 if (!null_db.OpenInMemory()) {
1048 DLOG(FATAL) << "Unable to open in-memory database.";
1049 return false;
1050 }
1051
[email protected]6d42f152012-11-10 00:38:241052 if (page_size_) {
1053 // Enforce SQLite restrictions on |page_size_|.
1054 DCHECK(!(page_size_ & (page_size_ - 1)))
1055 << " page_size_ " << page_size_ << " is not a power of two.";
1056 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1057 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041058 const std::string sql =
1059 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:421060 if (!null_db.Execute(sql.c_str()))
1061 return false;
1062 }
1063
[email protected]6d42f152012-11-10 00:38:241064#if defined(OS_ANDROID)
1065 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1066 // in-memory databases do not respect this define.
1067 // TODO(shess): Figure out a way to set this without using platform
1068 // specific code. AFAICT from sqlite3.c, the only way to do it
1069 // would be to create an actual filesystem database, which is
1070 // unfortunate.
1071 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1072 return false;
1073#endif
[email protected]8e0c01282012-04-06 19:36:491074
1075 // The page size doesn't take effect until a database has pages, and
1076 // at this point the null database has none. Changing the schema
1077 // version will create the first page. This will not affect the
1078 // schema version in the resulting database, as SQLite's backup
1079 // implementation propagates the schema version from the original
1080 // connection to the new version of the database, incremented by one
1081 // so that other readers see the schema change and act accordingly.
1082 if (!null_db.Execute("PRAGMA schema_version = 1"))
1083 return false;
1084
[email protected]6d42f152012-11-10 00:38:241085 // SQLite tracks the expected number of database pages in the first
1086 // page, and if it does not match the total retrieved from a
1087 // filesystem call, treats the database as corrupt. This situation
1088 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1089 // used to hint to SQLite to soldier on in that case, specifically
1090 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1091 // sqlite3.c lockBtree().]
1092 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1093 // page_size" can be used to query such a database.
1094 ScopedWritableSchema writable_schema(db_);
1095
[email protected]7bae5742013-07-10 20:46:161096 const char* kMain = "main";
1097 int rc = BackupDatabase(null_db.db_, db_, kMain);
1098 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:491099
1100 // The destination database was locked.
1101 if (rc == SQLITE_BUSY) {
1102 return false;
1103 }
1104
[email protected]7bae5742013-07-10 20:46:161105 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1106 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1107 // isn't even big enough for one page. Either way, reach in and
1108 // truncate it before trying again.
1109 // TODO(shess): Maybe it would be worthwhile to just truncate from
1110 // the get-go?
1111 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
1112 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:341113 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161114 if (rc != SQLITE_OK) {
1115 DLOG(FATAL) << "Failure getting file handle.";
1116 return false;
[email protected]7bae5742013-07-10 20:46:161117 }
1118
1119 rc = file->pMethods->xTruncate(file, 0);
1120 if (rc != SQLITE_OK) {
1121 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
1122 DLOG(FATAL) << "Failed to truncate file.";
1123 return false;
1124 }
1125
1126 rc = BackupDatabase(null_db.db_, db_, kMain);
1127 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
1128
1129 if (rc != SQLITE_DONE) {
1130 DLOG(FATAL) << "Failed retrying Raze().";
1131 }
1132 }
1133
[email protected]8e0c01282012-04-06 19:36:491134 // The entire database should have been backed up.
1135 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:161136 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:491137 DLOG(FATAL) << "Unable to copy entire null database.";
1138 return false;
1139 }
1140
[email protected]8e0c01282012-04-06 19:36:491141 return true;
1142}
1143
1144bool Connection::RazeWithTimout(base::TimeDelta timeout) {
1145 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381146 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491147 return false;
1148 }
1149
1150 ScopedBusyTimeout busy_timeout(db_);
1151 busy_timeout.SetTimeout(timeout);
1152 return Raze();
1153}
1154
[email protected]41a97c812013-02-07 02:35:381155bool Connection::RazeAndClose() {
1156 if (!db_) {
1157 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
1158 return false;
1159 }
1160
1161 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301162 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381163
1164 bool result = Raze();
1165
1166 CloseInternal(true);
1167
1168 // Mark the database so that future API calls fail appropriately,
1169 // but don't DCHECK (because after calling this function they are
1170 // expected to fail).
1171 poisoned_ = true;
1172
1173 return result;
1174}
1175
[email protected]8d409412013-07-19 18:25:301176void Connection::Poison() {
1177 if (!db_) {
1178 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
1179 return;
1180 }
1181
1182 RollbackAllTransactions();
1183 CloseInternal(true);
1184
1185 // Mark the database so that future API calls fail appropriately,
1186 // but don't DCHECK (because after calling this function they are
1187 // expected to fail).
1188 poisoned_ = true;
1189}
1190
[email protected]8d2e39e2013-06-24 05:55:081191// TODO(shess): To the extent possible, figure out the optimal
1192// ordering for these deletes which will prevent other connections
1193// from seeing odd behavior. For instance, it may be necessary to
1194// manually lock the main database file in a SQLite-compatible fashion
1195// (to prevent other processes from opening it), then delete the
1196// journal files, then delete the main database file. Another option
1197// might be to lock the main database file and poison the header with
1198// junk to prevent other processes from opening it successfully (like
1199// Gears "SQLite poison 3" trick).
1200//
1201// static
1202bool Connection::Delete(const base::FilePath& path) {
1203 base::ThreadRestrictions::AssertIOAllowed();
1204
1205 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
1206 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
1207
erg102ceb412015-06-20 01:38:131208 std::string journal_str = AsUTF8ForSQL(journal_path);
1209 std::string wal_str = AsUTF8ForSQL(wal_path);
1210 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081211
shess702467622015-09-16 19:04:551212 // Make sure sqlite3_initialize() is called before anything else.
1213 InitializeSqlite();
1214
erg102ceb412015-06-20 01:38:131215 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
1216 CHECK(vfs);
1217 CHECK(vfs->xDelete);
1218 CHECK(vfs->xAccess);
1219
1220 // We only work with unix, win32 and mojo filesystems. If you're trying to
1221 // use this code with any other VFS, you're not in a good place.
1222 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1223 strncmp(vfs->zName, "win32", 5) == 0 ||
1224 strcmp(vfs->zName, "mojo") == 0);
1225
1226 vfs->xDelete(vfs, journal_str.c_str(), 0);
1227 vfs->xDelete(vfs, wal_str.c_str(), 0);
1228 vfs->xDelete(vfs, path_str.c_str(), 0);
1229
1230 int journal_exists = 0;
1231 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
1232 &journal_exists);
1233
1234 int wal_exists = 0;
1235 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
1236 &wal_exists);
1237
1238 int path_exists = 0;
1239 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
1240 &path_exists);
1241
1242 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081243}
1244
[email protected]e5ffd0e42009-09-11 21:30:561245bool Connection::BeginTransaction() {
1246 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331247 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561248
1249 // When we're going to rollback, fail on this begin and don't actually
1250 // mark us as entering the nested transaction.
1251 return false;
1252 }
1253
1254 bool success = true;
1255 if (!transaction_nesting_) {
1256 needs_rollback_ = false;
1257
1258 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321259 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591260 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561261 return false;
1262 }
1263 transaction_nesting_++;
1264 return success;
1265}
1266
1267void Connection::RollbackTransaction() {
1268 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:381269 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561270 return;
1271 }
1272
1273 transaction_nesting_--;
1274
1275 if (transaction_nesting_ > 0) {
1276 // Mark the outermost transaction as needing rollback.
1277 needs_rollback_ = true;
1278 return;
1279 }
1280
1281 DoRollback();
1282}
1283
1284bool Connection::CommitTransaction() {
1285 if (!transaction_nesting_) {
shess90244e12015-11-09 22:08:181286 DLOG_IF(FATAL, !poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561287 return false;
1288 }
1289 transaction_nesting_--;
1290
1291 if (transaction_nesting_ > 0) {
1292 // Mark any nested transactions as failing after we've already got one.
1293 return !needs_rollback_;
1294 }
1295
1296 if (needs_rollback_) {
1297 DoRollback();
1298 return false;
1299 }
1300
1301 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321302
1303 // Collect the commit time manually, sql::Statement would register it as query
1304 // time only.
1305 const base::TimeTicks before = Now();
1306 bool ret = commit.RunWithoutTimers();
1307 const base::TimeDelta delta = Now() - before;
1308
1309 RecordCommitTime(delta);
1310 RecordOneEvent(EVENT_COMMIT);
1311
shess7dbd4dee2015-10-06 17:39:161312 // Release dirty cache pages after the transaction closes.
1313 ReleaseCacheMemoryIfNeeded(false);
1314
shess58b8df82015-06-03 00:19:321315 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561316}
1317
[email protected]8d409412013-07-19 18:25:301318void Connection::RollbackAllTransactions() {
1319 if (transaction_nesting_ > 0) {
1320 transaction_nesting_ = 0;
1321 DoRollback();
1322 }
1323}
1324
1325bool Connection::AttachDatabase(const base::FilePath& other_db_path,
1326 const char* attachment_point) {
1327 DCHECK(ValidAttachmentPoint(attachment_point));
1328
1329 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1330#if OS_WIN
1331 s.BindString16(0, other_db_path.value());
1332#else
1333 s.BindString(0, other_db_path.value());
1334#endif
1335 s.BindString(1, attachment_point);
1336 return s.Run();
1337}
1338
1339bool Connection::DetachDatabase(const char* attachment_point) {
1340 DCHECK(ValidAttachmentPoint(attachment_point));
1341
1342 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1343 s.BindString(0, attachment_point);
1344 return s.Run();
1345}
1346
shess58b8df82015-06-03 00:19:321347// TODO(shess): Consider changing this to execute exactly one statement. If a
1348// caller wishes to execute multiple statements, that should be explicit, and
1349// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591350int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501351 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381352 if (!db_) {
1353 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1354 return SQLITE_ERROR;
1355 }
shess58b8df82015-06-03 00:19:321356 DCHECK(sql);
1357
1358 RecordOneEvent(EVENT_EXECUTE);
1359 int rc = SQLITE_OK;
1360 while ((rc == SQLITE_OK) && *sql) {
1361 sqlite3_stmt *stmt = NULL;
1362 const char *leftover_sql;
1363
1364 const base::TimeTicks before = Now();
1365 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1366 sql = leftover_sql;
1367
1368 // Stop if an error is encountered.
1369 if (rc != SQLITE_OK)
1370 break;
1371
1372 // This happens if |sql| originally only contained comments or whitespace.
1373 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1374 // extraneous comments and whitespace in the SQL statements increases
1375 // runtime cost and can easily be shifted out to the C++ layer.
1376 if (!stmt)
1377 continue;
1378
1379 // Save for use after statement is finalized.
1380 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1381
1382 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1383 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1384 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1385 // is the only legitimate case for this.
1386 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1387 }
1388
1389 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1390 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1391 rc = sqlite3_finalize(stmt);
1392 if (rc == SQLITE_OK)
1393 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1394
1395 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1396 // trailing whitespace.
1397 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021398 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321399 sql++;
1400 }
1401
1402 const base::TimeDelta delta = Now() - before;
1403 RecordTimeAndChanges(delta, read_only);
1404 }
shess7dbd4dee2015-10-06 17:39:161405
1406 // Most calls to Execute() modify the database. The main exceptions would be
1407 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1408 // but sometimes don't.
1409 ReleaseCacheMemoryIfNeeded(true);
1410
shess58b8df82015-06-03 00:19:321411 return rc;
[email protected]eff1fa522011-12-12 23:50:591412}
1413
1414bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381415 if (!db_) {
1416 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1417 return false;
1418 }
1419
[email protected]eff1fa522011-12-12 23:50:591420 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001421 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581422 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001423
[email protected]28fe0ff2012-02-25 00:40:331424 // This needs to be a FATAL log because the error case of arriving here is
1425 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101426 // a change alters the schema but not all queries adjust. This can happen
1427 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:591428 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:331429 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591430 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561431}
1432
[email protected]5b96f3772010-09-28 16:30:571433bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381434 if (!db_) {
1435 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571436 return false;
[email protected]41a97c812013-02-07 02:35:381437 }
[email protected]5b96f3772010-09-28 16:30:571438
1439 ScopedBusyTimeout busy_timeout(db_);
1440 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591441 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571442}
1443
[email protected]e5ffd0e42009-09-11 21:30:561444bool Connection::HasCachedStatement(const StatementID& id) const {
1445 return statement_cache_.find(id) != statement_cache_.end();
1446}
1447
1448scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1449 const StatementID& id,
1450 const char* sql) {
1451 CachedStatementMap::iterator i = statement_cache_.find(id);
1452 if (i != statement_cache_.end()) {
1453 // Statement is in the cache. It should still be active (we're the only
1454 // one invalidating cached statements, and we'll remove it from the cache
1455 // if we do that. Make sure we reset it before giving out the cached one in
1456 // case it still has some stuff bound.
1457 DCHECK(i->second->is_valid());
1458 sqlite3_reset(i->second->stmt());
1459 return i->second;
1460 }
1461
1462 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1463 if (statement->is_valid())
1464 statement_cache_[id] = statement; // Only cache valid statements.
1465 return statement;
1466}
1467
1468scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1469 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501470 AssertIOAllowed();
1471
[email protected]41a97c812013-02-07 02:35:381472 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561473 if (!db_)
[email protected]41a97c812013-02-07 02:35:381474 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561475
1476 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001477 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1478 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591479 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061480 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021481 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001482
1483 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581484 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381485 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561486 }
[email protected]41a97c812013-02-07 02:35:381487 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561488}
1489
shessf7e988f2015-11-13 00:41:061490// TODO(shess): Unify this with GetUniqueStatement(). The only difference that
1491// seems legitimate is not passing |this| to StatementRef.
[email protected]2eec0a22012-07-24 01:59:581492scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1493 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:381494 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:581495 if (!db_)
[email protected]41a97c812013-02-07 02:35:381496 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:581497
1498 sqlite3_stmt* stmt = NULL;
1499 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1500 if (rc != SQLITE_OK) {
1501 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061502 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021503 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:381504 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:581505 }
[email protected]41a97c812013-02-07 02:35:381506 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:581507}
1508
[email protected]92cd00a2013-08-16 11:09:581509std::string Connection::GetSchema() const {
1510 // The ORDER BY should not be necessary, but relying on organic
1511 // order for something like this is questionable.
1512 const char* kSql =
1513 "SELECT type, name, tbl_name, sql "
1514 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1515 Statement statement(GetUntrackedStatement(kSql));
1516
1517 std::string schema;
1518 while (statement.Step()) {
1519 schema += statement.ColumnString(0);
1520 schema += '|';
1521 schema += statement.ColumnString(1);
1522 schema += '|';
1523 schema += statement.ColumnString(2);
1524 schema += '|';
1525 schema += statement.ColumnString(3);
1526 schema += '\n';
1527 }
1528
1529 return schema;
1530}
1531
[email protected]eff1fa522011-12-12 23:50:591532bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501533 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381534 if (!db_) {
1535 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1536 return false;
1537 }
1538
[email protected]eff1fa522011-12-12 23:50:591539 sqlite3_stmt* stmt = NULL;
1540 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1541 return false;
1542
1543 sqlite3_finalize(stmt);
1544 return true;
1545}
1546
[email protected]1ed78a32009-09-15 20:24:171547bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:531548 return DoesTableOrIndexExist(table_name, "table");
1549}
1550
1551bool Connection::DoesIndexExist(const char* index_name) const {
1552 return DoesTableOrIndexExist(index_name, "index");
1553}
1554
1555bool Connection::DoesTableOrIndexExist(
1556 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471557 const char* kSql =
1558 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581559 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471560
1561 // This can happen if the database is corrupt and the error is being ignored
1562 // for testing purposes.
1563 if (!statement.is_valid())
1564 return false;
1565
[email protected]e2cadec82011-12-13 02:00:531566 statement.BindString(0, type);
1567 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331568
[email protected]e5ffd0e42009-09-11 21:30:561569 return statement.Step(); // Table exists if any row was returned.
1570}
1571
1572bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171573 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561574 std::string sql("PRAGMA TABLE_INFO(");
1575 sql.append(table_name);
1576 sql.append(")");
1577
[email protected]2eec0a22012-07-24 01:59:581578 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471579
1580 // This can happen if the database is corrupt and the error is being ignored
1581 // for testing purposes.
1582 if (!statement.is_valid())
1583 return false;
1584
[email protected]e5ffd0e42009-09-11 21:30:561585 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331586 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1587 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561588 return true;
1589 }
1590 return false;
1591}
1592
tfarina720d4f32015-05-11 22:31:261593int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561594 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381595 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561596 return 0;
1597 }
1598 return sqlite3_last_insert_rowid(db_);
1599}
1600
[email protected]1ed78a32009-09-15 20:24:171601int Connection::GetLastChangeCount() const {
1602 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381603 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171604 return 0;
1605 }
1606 return sqlite3_changes(db_);
1607}
1608
[email protected]e5ffd0e42009-09-11 21:30:561609int Connection::GetErrorCode() const {
1610 if (!db_)
1611 return SQLITE_ERROR;
1612 return sqlite3_errcode(db_);
1613}
1614
[email protected]767718e52010-09-21 23:18:491615int Connection::GetLastErrno() const {
1616 if (!db_)
1617 return -1;
1618
1619 int err = 0;
1620 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1621 return -2;
1622
1623 return err;
1624}
1625
[email protected]e5ffd0e42009-09-11 21:30:561626const char* Connection::GetErrorMessage() const {
1627 if (!db_)
1628 return "sql::Connection has no connection.";
1629 return sqlite3_errmsg(db_);
1630}
1631
[email protected]fed734a2013-07-17 04:45:131632bool Connection::OpenInternal(const std::string& file_name,
1633 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501634 AssertIOAllowed();
1635
[email protected]9cfbc922009-11-17 20:13:171636 if (db_) {
[email protected]eff1fa522011-12-12 23:50:591637 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171638 return false;
1639 }
1640
[email protected]a7ec1292013-07-22 22:02:181641 // Make sure sqlite3_initialize() is called before anything else.
1642 InitializeSqlite();
1643
shess58b8df82015-06-03 00:19:321644 // Setup the stats histograms immediately rather than allocating lazily.
1645 // Connections which won't exercise all of these probably shouldn't exist.
1646 if (!histogram_tag_.empty()) {
1647 stats_histogram_ =
1648 base::LinearHistogram::FactoryGet(
1649 "Sqlite.Stats." + histogram_tag_,
1650 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1651 base::HistogramBase::kUmaTargetedHistogramFlag);
1652
1653 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1654 // unreasonable time for any single operation, so there is not much value to
1655 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1656 // things are entirely busted.
1657 commit_time_histogram_ =
1658 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1659
1660 autocommit_time_histogram_ =
1661 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1662
1663 update_time_histogram_ =
1664 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1665
1666 query_time_histogram_ =
1667 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1668 }
1669
[email protected]41a97c812013-02-07 02:35:381670 // If |poisoned_| is set, it means an error handler called
1671 // RazeAndClose(). Until regular Close() is called, the caller
1672 // should be treating the database as open, but is_open() currently
1673 // only considers the sqlite3 handle's state.
1674 // TODO(shess): Revise is_open() to consider poisoned_, and review
1675 // to see if any non-testing code even depends on it.
1676 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161677 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381678
[email protected]765b44502009-10-02 05:01:421679 int err = sqlite3_open(file_name.c_str(), &db_);
1680 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281681 // Extended error codes cannot be enabled until a handle is
1682 // available, fetch manually.
1683 err = sqlite3_extended_errcode(db_);
1684
[email protected]bd2ccdb4a2012-12-07 22:14:501685 // Histogram failures specific to initial open for debugging
1686 // purposes.
[email protected]73fb8d52013-07-24 05:04:281687 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501688
[email protected]2f496b42013-09-26 18:36:581689 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131690 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291691 Close();
[email protected]fed734a2013-07-17 04:45:131692
1693 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1694 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421695 return false;
1696 }
1697
[email protected]81a2a602013-07-17 19:10:361698 // TODO(shess): OS_WIN support?
1699#if defined(OS_POSIX)
1700 if (restrict_to_user_) {
1701 DCHECK_NE(file_name, std::string(":memory"));
1702 base::FilePath file_path(file_name);
1703 int mode = 0;
1704 // TODO(shess): Arguably, failure to retrieve and change
1705 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081706 if (base::GetPosixFilePermissions(file_path, &mode)) {
1707 mode &= base::FILE_PERMISSION_USER_MASK;
1708 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361709
1710 // SQLite sets the permissions on these files from the main
1711 // database on create. Set them here in case they already exist
1712 // at this point. Failure to set these permissions should not
1713 // be fatal unless the file doesn't exist.
1714 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1715 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081716 base::SetPosixFilePermissions(journal_path, mode);
1717 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361718 }
1719 }
1720#endif // defined(OS_POSIX)
1721
[email protected]affa2da2013-06-06 22:20:341722 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1723 // Chromium already depends on small mallocs being efficient, so we disable
1724 // this to avoid the extra memory overhead.
1725 // This must be called immediatly after opening the database before any SQL
1726 // statements are run.
1727 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1728
[email protected]73fb8d52013-07-24 05:04:281729 // Enable extended result codes to provide more color on I/O errors.
1730 // Not having extended result codes is not a fatal problem, as
1731 // Chromium code does not attempt to handle I/O errors anyhow. The
1732 // current implementation always returns SQLITE_OK, the DCHECK is to
1733 // quickly notify someone if SQLite changes.
1734 err = sqlite3_extended_result_codes(db_, 1);
1735 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1736
[email protected]bd2ccdb4a2012-12-07 22:14:501737 // sqlite3_open() does not actually read the database file (unless a
1738 // hot journal is found). Successfully executing this pragma on an
1739 // existing database requires a valid header on page 1.
1740 // TODO(shess): For now, just probing to see what the lay of the
1741 // land is. If it's mostly SQLITE_NOTADB, then the database should
1742 // be razed.
1743 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1744 if (err != SQLITE_OK)
[email protected]73fb8d52013-07-24 05:04:281745 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err);
[email protected]658f8332010-09-18 04:40:431746
[email protected]2e1cee762013-07-09 14:40:001747#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1748 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1749 // REGEXP support. Add it in dynamically.
1750 err = sqlite3IcuInit(db_);
1751 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1752#endif // OS_IOS && USE_SYSTEM_SQLITE
1753
[email protected]5b96f3772010-09-28 16:30:571754 // If indicated, lock up the database before doing anything else, so
1755 // that the following code doesn't have to deal with locking.
1756 // TODO(shess): This code is brittle. Find the cases where code
1757 // doesn't request |exclusive_locking_| and audit that it does the
1758 // right thing with SQLITE_BUSY, and that it doesn't make
1759 // assumptions about who might change things in the database.
1760 // http://crbug.com/56559
1761 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101762 // TODO(shess): This should probably be a failure. Code which
1763 // requests exclusive locking but doesn't get it is almost certain
1764 // to be ill-tested.
1765 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571766 }
1767
[email protected]4e179ba2012-03-17 16:06:471768 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1769 // DELETE (default) - delete -journal file to commit.
1770 // TRUNCATE - truncate -journal file to commit.
1771 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091772 // TRUNCATE should be faster than DELETE because it won't need directory
1773 // changes for each transaction. PERSIST may break the spirit of using
1774 // secure_delete.
1775 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba2012-03-17 16:06:471776
[email protected]c68ce172011-11-24 22:30:271777 const base::TimeDelta kBusyTimeout =
1778 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1779
[email protected]765b44502009-10-02 05:01:421780 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571781 // Enforce SQLite restrictions on |page_size_|.
1782 DCHECK(!(page_size_ & (page_size_ - 1)))
1783 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241784 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571785 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041786 const std::string sql =
1787 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101788 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421789 }
1790
1791 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041792 const std::string sql =
1793 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101794 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421795 }
1796
[email protected]6e0b1442011-08-09 23:23:581797 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131798 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581799 Close();
[email protected]fed734a2013-07-17 04:45:131800 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1801 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581802 return false;
1803 }
1804
shess5dac334f2015-11-05 20:47:421805 // Set a reasonable chunk size for larger files. This reduces churn from
1806 // remapping memory on size changes. It also reduces filesystem
1807 // fragmentation.
1808 // TODO(shess): It may make sense to have this be hinted by the client.
1809 // Database sizes seem to be bimodal, some clients have consistently small
1810 // databases (<20k) while other clients have a broad distribution of sizes
1811 // (hundreds of kilobytes to many megabytes).
1812 sqlite3_file* file = NULL;
1813 sqlite3_int64 db_size = 0;
1814 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1815 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1816 int chunk_size = 4 * 1024;
1817 if (db_size > 128 * 1024)
1818 chunk_size = 32 * 1024;
1819 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1820 }
1821
shess2f3a814b2015-11-05 18:11:101822 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311823 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1824 // safe range to memory-map based on past regular I/O. This value will be
1825 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1826 // 64-bit platforms.
1827 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1828 std::string mmap_sql =
1829 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1830 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101831
1832 // Determine if memory-mapping has actually been enabled. The Execute() above
1833 // can succeed without changing the amount mapped.
1834 mmap_enabled_ = false;
1835 {
1836 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1837 if (s.Step() && s.ColumnInt64(0) > 0)
1838 mmap_enabled_ = true;
1839 }
1840
ssid3be5b1ec2016-01-13 14:21:571841 DCHECK(!memory_dump_provider_);
1842 memory_dump_provider_.reset(
1843 new ConnectionMemoryDumpProvider(db_, histogram_tag_));
1844 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1845 memory_dump_provider_.get(), "sql::Connection", nullptr);
1846
[email protected]765b44502009-10-02 05:01:421847 return true;
1848}
1849
[email protected]e5ffd0e42009-09-11 21:30:561850void Connection::DoRollback() {
1851 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321852
1853 // Collect the rollback time manually, sql::Statement would register it as
1854 // query time only.
1855 const base::TimeTicks before = Now();
1856 rollback.RunWithoutTimers();
1857 const base::TimeDelta delta = Now() - before;
1858
1859 RecordUpdateTime(delta);
1860 RecordOneEvent(EVENT_ROLLBACK);
1861
shess7dbd4dee2015-10-06 17:39:161862 // The cache may have been accumulating dirty pages for commit. Note that in
1863 // some cases sql::Transaction can fire rollback after a database is closed.
1864 if (is_open())
1865 ReleaseCacheMemoryIfNeeded(false);
1866
[email protected]44ad7d902012-03-23 00:09:051867 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561868}
1869
1870void Connection::StatementRefCreated(StatementRef* ref) {
1871 DCHECK(open_statements_.find(ref) == open_statements_.end());
1872 open_statements_.insert(ref);
1873}
1874
1875void Connection::StatementRefDeleted(StatementRef* ref) {
1876 StatementRefSet::iterator i = open_statements_.find(ref);
1877 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:591878 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561879 else
1880 open_statements_.erase(i);
1881}
1882
shess58b8df82015-06-03 00:19:321883void Connection::set_histogram_tag(const std::string& tag) {
1884 DCHECK(!is_open());
1885 histogram_tag_ = tag;
1886}
1887
[email protected]210ce0af2013-05-15 09:10:391888void Connection::AddTaggedHistogram(const std::string& name,
1889 size_t sample) const {
1890 if (histogram_tag_.empty())
1891 return;
1892
1893 // TODO(shess): The histogram macros create a bit of static storage
1894 // for caching the histogram object. This code shouldn't execute
1895 // often enough for such caching to be crucial. If it becomes an
1896 // issue, the object could be cached alongside histogram_prefix_.
1897 std::string full_histogram_name = name + "." + histogram_tag_;
1898 base::HistogramBase* histogram =
1899 base::SparseHistogram::FactoryGet(
1900 full_histogram_name,
1901 base::HistogramBase::kUmaTargetedHistogramFlag);
1902 if (histogram)
1903 histogram->Add(sample);
1904}
1905
[email protected]2f496b42013-09-26 18:36:581906int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) {
[email protected]210ce0af2013-05-15 09:10:391907 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
1908 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141909
1910 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581911 if (!sql && stmt)
1912 sql = stmt->GetSQLStatement();
1913 if (!sql)
1914 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061915
1916 std::string id = histogram_tag_;
1917 if (id.empty())
1918 id = DbPath().BaseName().AsUTF8Unsafe();
1919 LOG(ERROR) << id << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141920 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581921 << ": " << GetErrorMessage()
1922 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141923
[email protected]c3881b372013-05-17 08:39:461924 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561925 // Fire from a copy of the callback in case of reentry into
1926 // re/set_error_callback().
1927 // TODO(shess): <http://crbug.com/254584>
1928 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461929 return err;
1930 }
1931
[email protected]faa604e2009-09-25 22:38:591932 // The default handling is to assert on debug and to ignore on release.
[email protected]74cdede2013-09-25 05:39:571933 if (!ShouldIgnoreSqliteError(err))
[email protected]4350e322013-06-18 22:18:101934 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591935 return err;
1936}
1937
[email protected]579446c2013-12-16 18:36:521938bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1939 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1940}
1941
1942bool Connection::QuickIntegrityCheck() {
1943 std::vector<std::string> messages;
1944 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1945 return false;
1946 return messages.size() == 1 && messages[0] == "ok";
1947}
1948
[email protected]80abf152013-05-22 12:42:421949// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521950bool Connection::IntegrityCheckHelper(
1951 const char* pragma_sql,
1952 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421953 messages->clear();
1954
[email protected]4658e2a02013-06-06 23:05:001955 // This has the side effect of setting SQLITE_RecoveryMode, which
1956 // allows SQLite to process through certain cases of corruption.
1957 // Failing to set this pragma probably means that the database is
1958 // beyond recovery.
1959 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1960 if (!Execute(kWritableSchema))
1961 return false;
1962
1963 bool ret = false;
1964 {
[email protected]579446c2013-12-16 18:36:521965 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001966
1967 // The pragma appears to return all results (up to 100 by default)
1968 // as a single string. This doesn't appear to be an API contract,
1969 // it could return separate lines, so loop _and_ split.
1970 while (stmt.Step()) {
1971 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181972 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1973 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001974 }
1975 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421976 }
[email protected]4658e2a02013-06-06 23:05:001977
1978 // Best effort to put things back as they were before.
1979 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1980 ignore_result(Execute(kNoWritableSchema));
1981
1982 return ret;
[email protected]80abf152013-05-22 12:42:421983}
1984
shess58b8df82015-06-03 00:19:321985base::TimeTicks TimeSource::Now() {
1986 return base::TimeTicks::Now();
1987}
1988
[email protected]e5ffd0e42009-09-11 21:30:561989} // namespace sql