blob: b17da0dde2f7f00fe199ee72ad37f8dcbadcc5b7 [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>
mostynbd82cd9952016-04-11 20:05:3411
dchenge48600452015-12-28 02:24:5012#include <utility>
[email protected]e5ffd0e42009-09-11 21:30:5613
shessc9e80ae22015-08-12 21:39:1114#include "base/bind.h"
shessc8cd2a162015-10-22 20:30:4615#include "base/debug/dump_without_crashing.h"
[email protected]57999812013-02-24 05:40:5216#include "base/files/file_path.h"
thestig22dfc4012014-09-05 08:29:4417#include "base/files/file_util.h"
shessc8cd2a162015-10-22 20:30:4618#include "base/format_macros.h"
19#include "base/json/json_file_value_serializer.h"
[email protected]a7ec1292013-07-22 22:02:1820#include "base/lazy_instance.h"
[email protected]e5ffd0e42009-09-11 21:30:5621#include "base/logging.h"
shessc9e80ae22015-08-12 21:39:1122#include "base/message_loop/message_loop.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5023#include "base/metrics/histogram.h"
[email protected]210ce0af2013-05-15 09:10:3924#include "base/metrics/sparse_histogram.h"
[email protected]80abf152013-05-22 12:42:4225#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1926#include "base/strings/string_util.h"
27#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4528#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1829#include "base/synchronization/lock.h"
ssid9f8022f2015-10-12 17:49:0330#include "base/trace_event/memory_dump_manager.h"
ssid3be5b1ec2016-01-13 14:21:5731#include "sql/connection_memory_dump_provider.h"
shess9bf2c672015-12-18 01:18:0832#include "sql/meta_table.h"
[email protected]f0a54b22011-07-19 18:40:2133#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0334#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5635
[email protected]2e1cee762013-07-09 14:40:0036#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
37#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
38#endif
39
[email protected]5b96f3772010-09-28 16:30:5740namespace {
41
42// Spin for up to a second waiting for the lock to clear when setting
43// up the database.
44// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2745const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5746
vichang7ce37c12016-01-28 22:09:0347bool g_mmap_disabled_default = false;
48
[email protected]5b96f3772010-09-28 16:30:5749class ScopedBusyTimeout {
50 public:
51 explicit ScopedBusyTimeout(sqlite3* db)
52 : db_(db) {
53 }
54 ~ScopedBusyTimeout() {
55 sqlite3_busy_timeout(db_, 0);
56 }
57
58 int SetTimeout(base::TimeDelta timeout) {
59 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
60 return sqlite3_busy_timeout(db_,
61 static_cast<int>(timeout.InMilliseconds()));
62 }
63
64 private:
65 sqlite3* db_;
66};
67
[email protected]6d42f152012-11-10 00:38:2468// Helper to "safely" enable writable_schema. No error checking
69// because it is reasonable to just forge ahead in case of an error.
70// If turning it on fails, then most likely nothing will work, whereas
71// if turning it off fails, it only matters if some code attempts to
72// continue working with the database and tries to modify the
73// sqlite_master table (none of our code does this).
74class ScopedWritableSchema {
75 public:
76 explicit ScopedWritableSchema(sqlite3* db)
77 : db_(db) {
78 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
79 }
80 ~ScopedWritableSchema() {
81 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
82 }
83
84 private:
85 sqlite3* db_;
86};
87
[email protected]7bae5742013-07-10 20:46:1688// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
89// SQLite error code from running the backup step.
90int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
91 DCHECK_NE(src, dst);
92 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
93 if (!backup) {
94 // Since this call only sets things up, this indicates a gross
95 // error in SQLite.
96 DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
97 return sqlite3_errcode(dst);
98 }
99
100 // -1 backs up the entire database.
101 int rc = sqlite3_backup_step(backup, -1);
102 int pages = sqlite3_backup_pagecount(backup);
103 sqlite3_backup_finish(backup);
104
105 // If successful, exactly one page should have been backed up. If
106 // this breaks, check this function to make sure assumptions aren't
107 // being broken.
108 if (rc == SQLITE_DONE)
109 DCHECK_EQ(pages, 1);
110
111 return rc;
112}
113
[email protected]8d409412013-07-19 18:25:30114// Be very strict on attachment point. SQLite can handle a much wider
115// character set with appropriate quoting, but Chromium code should
116// just use clean names to start with.
117bool ValidAttachmentPoint(const char* attachment_point) {
118 for (size_t i = 0; attachment_point[i]; ++i) {
zhongyi23960342016-04-12 23:13:20119 if (!(base::IsAsciiDigit(attachment_point[i]) ||
120 base::IsAsciiAlpha(attachment_point[i]) ||
[email protected]8d409412013-07-19 18:25:30121 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]4e179ba62012-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
mostynbd82cd9952016-04-11 20:05:34545 std::unique_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
mostynbd82cd9952016-04-11 20:05:34682 std::unique_ptr<base::Value> root;
shessc8cd2a162015-10-22 20:30:46683 if (!base::PathExists(breadcrumb_path)) {
mostynbd82cd9952016-04-11 20:05:34684 std::unique_ptr<base::DictionaryValue> root_dict(
685 new base::DictionaryValue());
shessc8cd2a162015-10-22 20:30:46686 root_dict->SetInteger(kVersionKey, kVersion);
687
mostynbd82cd9952016-04-11 20:05:34688 std::unique_ptr<base::ListValue> dumps(new base::ListValue);
shessc8cd2a162015-10-22 20:30:46689 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50690 root_dict->Set(kDiagnosticDumpsKey, std::move(dumps));
shessc8cd2a162015-10-22 20:30:46691
dchenge48600452015-12-28 02:24:50692 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46693 } else {
694 // Failure to read a valid dictionary implies that something is going wrong
695 // on the system.
696 JSONFileValueDeserializer deserializer(breadcrumb_path);
mostynbd82cd9952016-04-11 20:05:34697 std::unique_ptr<base::Value> read_root(
shessc8cd2a162015-10-22 20:30:46698 deserializer.Deserialize(nullptr, nullptr));
699 if (!read_root.get())
700 return false;
mostynbd82cd9952016-04-11 20:05:34701 std::unique_ptr<base::DictionaryValue> root_dict =
dchenge48600452015-12-28 02:24:50702 base::DictionaryValue::From(std::move(read_root));
shessc8cd2a162015-10-22 20:30:46703 if (!root_dict)
704 return false;
705
706 // Don't upload if the version is missing or newer.
707 int version = 0;
708 if (!root_dict->GetInteger(kVersionKey, &version) || version > kVersion)
709 return false;
710
711 base::ListValue* dumps = nullptr;
712 if (!root_dict->GetList(kDiagnosticDumpsKey, &dumps))
713 return false;
714
715 const size_t size = dumps->GetSize();
716 for (size_t i = 0; i < size; ++i) {
717 std::string s;
718
719 // Don't upload if the value isn't a string, or indicates a prior upload.
720 if (!dumps->GetString(i, &s) || s == histogram_tag_)
721 return false;
722 }
723
724 // Record intention to proceed with upload.
725 dumps->AppendString(histogram_tag_);
dchenge48600452015-12-28 02:24:50726 root = std::move(root_dict);
shessc8cd2a162015-10-22 20:30:46727 }
728
729 const base::FilePath breadcrumb_new =
730 breadcrumb_path.AddExtension(FILE_PATH_LITERAL("new"));
731 base::DeleteFile(breadcrumb_new, false);
732
733 // No upload if the breadcrumb file cannot be updated.
734 // TODO(shess): Consider ImportantFileWriter::WriteFileAtomically() to land
735 // the data on disk. For now, losing the data is not a big problem, so the
736 // sync overhead would probably not be worth it.
737 JSONFileValueSerializer serializer(breadcrumb_new);
738 if (!serializer.Serialize(*root))
739 return false;
740 if (!base::PathExists(breadcrumb_new))
741 return false;
742 if (!base::ReplaceFile(breadcrumb_new, breadcrumb_path, nullptr)) {
743 base::DeleteFile(breadcrumb_new, false);
744 return false;
745 }
746
747 return true;
748}
749
750std::string Connection::CollectErrorInfo(int error, Statement* stmt) const {
751 // Buffer for accumulating debugging info about the error. Place
752 // more-relevant information earlier, in case things overflow the
753 // fixed-size reporting buffer.
754 std::string debug_info;
755
756 // The error message from the failed operation.
757 base::StringAppendF(&debug_info, "db error: %d/%s\n",
758 GetErrorCode(), GetErrorMessage());
759
760 // TODO(shess): |error| and |GetErrorCode()| should always be the same, but
761 // reading code does not entirely convince me. Remove if they turn out to be
762 // the same.
763 if (error != GetErrorCode())
764 base::StringAppendF(&debug_info, "reported error: %d\n", error);
765
766 // System error information. Interpretation of Windows errors is different
767 // from posix.
768#if defined(OS_WIN)
769 base::StringAppendF(&debug_info, "LastError: %d\n", GetLastErrno());
770#elif defined(OS_POSIX)
771 base::StringAppendF(&debug_info, "errno: %d\n", GetLastErrno());
772#else
773 NOTREACHED(); // Add appropriate log info.
774#endif
775
776 if (stmt) {
777 base::StringAppendF(&debug_info, "statement: %s\n",
778 stmt->GetSQLStatement());
779 } else {
780 base::StringAppendF(&debug_info, "statement: NULL\n");
781 }
782
783 // SQLITE_ERROR often indicates some sort of mismatch between the statement
784 // and the schema, possibly due to a failed schema migration.
785 if (error == SQLITE_ERROR) {
786 const char* kVersionSql = "SELECT value FROM meta WHERE key = 'version'";
787 sqlite3_stmt* s;
788 int rc = sqlite3_prepare_v2(db_, kVersionSql, -1, &s, nullptr);
789 if (rc == SQLITE_OK) {
790 rc = sqlite3_step(s);
791 if (rc == SQLITE_ROW) {
792 base::StringAppendF(&debug_info, "version: %d\n",
793 sqlite3_column_int(s, 0));
794 } else if (rc == SQLITE_DONE) {
795 debug_info += "version: none\n";
796 } else {
797 base::StringAppendF(&debug_info, "version: error %d\n", rc);
798 }
799 sqlite3_finalize(s);
800 } else {
801 base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
802 }
803
804 debug_info += "schema:\n";
805
806 // sqlite_master has columns:
807 // type - "index" or "table".
808 // name - name of created element.
809 // tbl_name - name of element, or target table in case of index.
810 // rootpage - root page of the element in database file.
811 // sql - SQL to create the element.
812 // In general, the |sql| column is sufficient to derive the other columns.
813 // |rootpage| is not interesting for debugging, without the contents of the
814 // database. The COALESCE is because certain automatic elements will have a
815 // |name| but no |sql|,
816 const char* kSchemaSql = "SELECT COALESCE(sql, name) FROM sqlite_master";
817 rc = sqlite3_prepare_v2(db_, kSchemaSql, -1, &s, nullptr);
818 if (rc == SQLITE_OK) {
819 while ((rc = sqlite3_step(s)) == SQLITE_ROW) {
820 base::StringAppendF(&debug_info, "%s\n", sqlite3_column_text(s, 0));
821 }
822 if (rc != SQLITE_DONE)
823 base::StringAppendF(&debug_info, "error %d\n", rc);
824 sqlite3_finalize(s);
825 } else {
826 base::StringAppendF(&debug_info, "prepare error %d\n", rc);
827 }
828 }
829
830 return debug_info;
831}
832
833// TODO(shess): Since this is only called in an error situation, it might be
834// prudent to rewrite in terms of SQLite API calls, and mark the function const.
835std::string Connection::CollectCorruptionInfo() {
836 AssertIOAllowed();
837
838 // If the file cannot be accessed it is unlikely that an integrity check will
839 // turn up actionable information.
840 const base::FilePath db_path = DbPath();
avi0b519202015-12-21 07:25:19841 int64_t db_size = -1;
shessc8cd2a162015-10-22 20:30:46842 if (!base::GetFileSize(db_path, &db_size) || db_size < 0)
843 return std::string();
844
845 // Buffer for accumulating debugging info about the error. Place
846 // more-relevant information earlier, in case things overflow the
847 // fixed-size reporting buffer.
848 std::string debug_info;
849 base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
850 db_size);
851
852 // Only check files up to 8M to keep things from blocking too long.
avi0b519202015-12-21 07:25:19853 const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
shessc8cd2a162015-10-22 20:30:46854 if (db_size > kMaxIntegrityCheckSize) {
855 debug_info += "integrity_check skipped due to size\n";
856 } else {
857 std::vector<std::string> messages;
858
859 // TODO(shess): FullIntegrityCheck() splits into a vector while this joins
860 // into a string. Probably should be refactored.
861 const base::TimeTicks before = base::TimeTicks::Now();
862 FullIntegrityCheck(&messages);
863 base::StringAppendF(
864 &debug_info,
865 "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
866 (base::TimeTicks::Now() - before).InMilliseconds(),
867 messages.size());
868
869 // SQLite returns up to 100 messages by default, trim deeper to
870 // keep close to the 2000-character size limit for dumping.
871 const size_t kMaxMessages = 20;
872 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
873 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
874 }
875 }
876
877 return debug_info;
878}
879
shessd90aeea82015-11-13 02:24:31880size_t Connection::GetAppropriateMmapSize() {
881 AssertIOAllowed();
882
shessd90aeea82015-11-13 02:24:31883#if defined(OS_IOS)
884 // iOS SQLite does not support memory mapping.
885 return 0;
886#endif
887
shess9bf2c672015-12-18 01:18:08888 // How much to map if no errors are found. 50MB encompasses the 99th
889 // percentile of Chrome databases in the wild, so this should be good.
890 const size_t kMmapEverything = 256 * 1024 * 1024;
891
892 // If the database doesn't have a place to track progress, assume the best.
893 // This will happen when new databases are created, or if a database doesn't
894 // use a meta table. sql::MetaTable::Init() will preload kMmapSuccess.
895 // TODO(shess): Databases not using meta include:
896 // DOMStorageDatabase (localstorage)
897 // ActivityDatabase (extensions activity log)
898 // PredictorDatabase (prefetch and autocomplete predictor data)
899 // SyncDirectory (sync metadata storage)
900 // For now, these all have mmap disabled to allow other databases to get the
901 // default-enable path. sqlite-diag could be an alternative for all but
902 // DOMStorageDatabase, which creates many small databases.
903 // http://crbug.com/537742
904 if (!MetaTable::DoesTableExist(this)) {
shessd90aeea82015-11-13 02:24:31905 RecordOneEvent(EVENT_MMAP_META_MISSING);
shess9bf2c672015-12-18 01:18:08906 return kMmapEverything;
shessd90aeea82015-11-13 02:24:31907 }
908
shess9bf2c672015-12-18 01:18:08909 int64_t mmap_ofs = 0;
910 if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
911 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
912 return 0;
shessd90aeea82015-11-13 02:24:31913 }
914
915 // Database read failed in the past, don't memory map.
shess9bf2c672015-12-18 01:18:08916 if (mmap_ofs == MetaTable::kMmapFailure) {
shessd90aeea82015-11-13 02:24:31917 RecordOneEvent(EVENT_MMAP_FAILED);
918 return 0;
shess9bf2c672015-12-18 01:18:08919 } else if (mmap_ofs != MetaTable::kMmapSuccess) {
shessd90aeea82015-11-13 02:24:31920 // Continue reading from previous offset.
921 DCHECK_GE(mmap_ofs, 0);
922
923 // TODO(shess): Could this reading code be shared with Preload()? It would
924 // require locking twice (this code wouldn't be able to access |db_size| so
925 // the helper would have to return amount read).
926
927 // Read more of the database looking for errors. The VFS interface is used
928 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
929 // to limit checking to 20MB per run of Chromium.
930 sqlite3_file* file = NULL;
931 sqlite3_int64 db_size = 0;
932 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
933 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
934 return 0;
935 }
936
937 // Read the data left, or |g_reads_allowed|, whichever is smaller.
938 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
939 // in a single Chromium run.
940 sqlite3_int64 amount = db_size - mmap_ofs;
941 if (amount < 0)
942 amount = 0;
943 if (amount > 0) {
944 base::AutoLock lock(g_sqlite_init_lock.Get());
945 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
946 if (g_reads_allowed < amount)
947 amount = g_reads_allowed;
948 g_reads_allowed -= amount;
949 }
950
951 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
952 // database was truncated after a previous pass.
953 if (amount <= 0 && mmap_ofs < db_size) {
954 DCHECK_EQ(0, amount);
955 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
956 } else {
957 static const int kPageSize = 4096;
958 char buf[kPageSize];
959 while (amount > 0) {
960 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
961 if (rc == SQLITE_OK) {
962 mmap_ofs += sizeof(buf);
963 amount -= sizeof(buf);
964 } else if (rc == SQLITE_IOERR_SHORT_READ) {
965 // Reached EOF for a database with page size < |kPageSize|.
966 mmap_ofs = db_size;
967 break;
968 } else {
969 // TODO(shess): Consider calling OnSqliteError().
shess9bf2c672015-12-18 01:18:08970 mmap_ofs = MetaTable::kMmapFailure;
shessd90aeea82015-11-13 02:24:31971 break;
972 }
973 }
974
975 // Log these events after update to distinguish meta update failure.
976 Events event;
977 if (mmap_ofs >= db_size) {
shess9bf2c672015-12-18 01:18:08978 mmap_ofs = MetaTable::kMmapSuccess;
shessd90aeea82015-11-13 02:24:31979 event = EVENT_MMAP_SUCCESS_NEW;
980 } else if (mmap_ofs > 0) {
981 event = EVENT_MMAP_SUCCESS_PARTIAL;
982 } else {
shess9bf2c672015-12-18 01:18:08983 DCHECK_EQ(MetaTable::kMmapFailure, mmap_ofs);
shessd90aeea82015-11-13 02:24:31984 event = EVENT_MMAP_FAILED_NEW;
985 }
986
shess9bf2c672015-12-18 01:18:08987 if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
shessd90aeea82015-11-13 02:24:31988 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
989 return 0;
990 }
991
992 RecordOneEvent(event);
993 }
994 }
995
shess9bf2c672015-12-18 01:18:08996 if (mmap_ofs == MetaTable::kMmapFailure)
shessd90aeea82015-11-13 02:24:31997 return 0;
shess9bf2c672015-12-18 01:18:08998 if (mmap_ofs == MetaTable::kMmapSuccess)
999 return kMmapEverything;
shessd90aeea82015-11-13 02:24:311000 return mmap_ofs;
1001}
1002
[email protected]be7995f12013-07-18 18:49:141003void Connection::TrimMemory(bool aggressively) {
1004 if (!db_)
1005 return;
1006
1007 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
1008 int original_cache_size;
1009 {
1010 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
1011 if (!sql_get_original.Step()) {
1012 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
1013 return;
1014 }
1015 original_cache_size = sql_get_original.ColumnInt(0);
1016 }
1017 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
1018
1019 // Force sqlite to try to reduce page cache usage.
1020 const std::string sql_shrink =
1021 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
1022 if (!Execute(sql_shrink.c_str()))
1023 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
1024
1025 // Restore cache size.
1026 const std::string sql_restore =
1027 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
1028 if (!Execute(sql_restore.c_str()))
1029 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
1030}
1031
[email protected]8e0c01282012-04-06 19:36:491032// Create an in-memory database with the existing database's page
1033// size, then backup that database over the existing database.
1034bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:501035 AssertIOAllowed();
1036
[email protected]8e0c01282012-04-06 19:36:491037 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381038 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491039 return false;
1040 }
1041
1042 if (transaction_nesting_ > 0) {
1043 DLOG(FATAL) << "Cannot raze within a transaction";
1044 return false;
1045 }
1046
1047 sql::Connection null_db;
1048 if (!null_db.OpenInMemory()) {
1049 DLOG(FATAL) << "Unable to open in-memory database.";
1050 return false;
1051 }
1052
[email protected]6d42f152012-11-10 00:38:241053 if (page_size_) {
1054 // Enforce SQLite restrictions on |page_size_|.
1055 DCHECK(!(page_size_ & (page_size_ - 1)))
1056 << " page_size_ " << page_size_ << " is not a power of two.";
1057 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1058 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041059 const std::string sql =
1060 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:421061 if (!null_db.Execute(sql.c_str()))
1062 return false;
1063 }
1064
[email protected]6d42f152012-11-10 00:38:241065#if defined(OS_ANDROID)
1066 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
1067 // in-memory databases do not respect this define.
1068 // TODO(shess): Figure out a way to set this without using platform
1069 // specific code. AFAICT from sqlite3.c, the only way to do it
1070 // would be to create an actual filesystem database, which is
1071 // unfortunate.
1072 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
1073 return false;
1074#endif
[email protected]8e0c01282012-04-06 19:36:491075
1076 // The page size doesn't take effect until a database has pages, and
1077 // at this point the null database has none. Changing the schema
1078 // version will create the first page. This will not affect the
1079 // schema version in the resulting database, as SQLite's backup
1080 // implementation propagates the schema version from the original
1081 // connection to the new version of the database, incremented by one
1082 // so that other readers see the schema change and act accordingly.
1083 if (!null_db.Execute("PRAGMA schema_version = 1"))
1084 return false;
1085
[email protected]6d42f152012-11-10 00:38:241086 // SQLite tracks the expected number of database pages in the first
1087 // page, and if it does not match the total retrieved from a
1088 // filesystem call, treats the database as corrupt. This situation
1089 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
1090 // used to hint to SQLite to soldier on in that case, specifically
1091 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
1092 // sqlite3.c lockBtree().]
1093 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
1094 // page_size" can be used to query such a database.
1095 ScopedWritableSchema writable_schema(db_);
1096
[email protected]7bae5742013-07-10 20:46:161097 const char* kMain = "main";
1098 int rc = BackupDatabase(null_db.db_, db_, kMain);
1099 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:491100
1101 // The destination database was locked.
1102 if (rc == SQLITE_BUSY) {
1103 return false;
1104 }
1105
[email protected]7bae5742013-07-10 20:46:161106 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
1107 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
1108 // isn't even big enough for one page. Either way, reach in and
1109 // truncate it before trying again.
1110 // TODO(shess): Maybe it would be worthwhile to just truncate from
1111 // the get-go?
1112 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
1113 sqlite3_file* file = NULL;
[email protected]8ada10f2013-12-21 00:42:341114 rc = GetSqlite3File(db_, &file);
[email protected]7bae5742013-07-10 20:46:161115 if (rc != SQLITE_OK) {
1116 DLOG(FATAL) << "Failure getting file handle.";
1117 return false;
[email protected]7bae5742013-07-10 20:46:161118 }
1119
1120 rc = file->pMethods->xTruncate(file, 0);
1121 if (rc != SQLITE_OK) {
1122 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
1123 DLOG(FATAL) << "Failed to truncate file.";
1124 return false;
1125 }
1126
1127 rc = BackupDatabase(null_db.db_, db_, kMain);
1128 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
1129
1130 if (rc != SQLITE_DONE) {
1131 DLOG(FATAL) << "Failed retrying Raze().";
1132 }
1133 }
1134
[email protected]8e0c01282012-04-06 19:36:491135 // The entire database should have been backed up.
1136 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:161137 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:491138 DLOG(FATAL) << "Unable to copy entire null database.";
1139 return false;
1140 }
1141
[email protected]8e0c01282012-04-06 19:36:491142 return true;
1143}
1144
1145bool Connection::RazeWithTimout(base::TimeDelta timeout) {
1146 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381147 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:491148 return false;
1149 }
1150
1151 ScopedBusyTimeout busy_timeout(db_);
1152 busy_timeout.SetTimeout(timeout);
1153 return Raze();
1154}
1155
[email protected]41a97c812013-02-07 02:35:381156bool Connection::RazeAndClose() {
1157 if (!db_) {
1158 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
1159 return false;
1160 }
1161
1162 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:301163 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:381164
1165 bool result = Raze();
1166
1167 CloseInternal(true);
1168
1169 // Mark the database so that future API calls fail appropriately,
1170 // but don't DCHECK (because after calling this function they are
1171 // expected to fail).
1172 poisoned_ = true;
1173
1174 return result;
1175}
1176
[email protected]8d409412013-07-19 18:25:301177void Connection::Poison() {
1178 if (!db_) {
1179 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
1180 return;
1181 }
1182
1183 RollbackAllTransactions();
1184 CloseInternal(true);
1185
1186 // Mark the database so that future API calls fail appropriately,
1187 // but don't DCHECK (because after calling this function they are
1188 // expected to fail).
1189 poisoned_ = true;
1190}
1191
[email protected]8d2e39e2013-06-24 05:55:081192// TODO(shess): To the extent possible, figure out the optimal
1193// ordering for these deletes which will prevent other connections
1194// from seeing odd behavior. For instance, it may be necessary to
1195// manually lock the main database file in a SQLite-compatible fashion
1196// (to prevent other processes from opening it), then delete the
1197// journal files, then delete the main database file. Another option
1198// might be to lock the main database file and poison the header with
1199// junk to prevent other processes from opening it successfully (like
1200// Gears "SQLite poison 3" trick).
1201//
1202// static
1203bool Connection::Delete(const base::FilePath& path) {
1204 base::ThreadRestrictions::AssertIOAllowed();
1205
1206 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
1207 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
1208
erg102ceb412015-06-20 01:38:131209 std::string journal_str = AsUTF8ForSQL(journal_path);
1210 std::string wal_str = AsUTF8ForSQL(wal_path);
1211 std::string path_str = AsUTF8ForSQL(path);
[email protected]8d2e39e2013-06-24 05:55:081212
shess702467622015-09-16 19:04:551213 // Make sure sqlite3_initialize() is called before anything else.
1214 InitializeSqlite();
1215
erg102ceb412015-06-20 01:38:131216 sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
1217 CHECK(vfs);
1218 CHECK(vfs->xDelete);
1219 CHECK(vfs->xAccess);
1220
1221 // We only work with unix, win32 and mojo filesystems. If you're trying to
1222 // use this code with any other VFS, you're not in a good place.
1223 CHECK(strncmp(vfs->zName, "unix", 4) == 0 ||
1224 strncmp(vfs->zName, "win32", 5) == 0 ||
1225 strcmp(vfs->zName, "mojo") == 0);
1226
1227 vfs->xDelete(vfs, journal_str.c_str(), 0);
1228 vfs->xDelete(vfs, wal_str.c_str(), 0);
1229 vfs->xDelete(vfs, path_str.c_str(), 0);
1230
1231 int journal_exists = 0;
1232 vfs->xAccess(vfs, journal_str.c_str(), SQLITE_ACCESS_EXISTS,
1233 &journal_exists);
1234
1235 int wal_exists = 0;
1236 vfs->xAccess(vfs, wal_str.c_str(), SQLITE_ACCESS_EXISTS,
1237 &wal_exists);
1238
1239 int path_exists = 0;
1240 vfs->xAccess(vfs, path_str.c_str(), SQLITE_ACCESS_EXISTS,
1241 &path_exists);
1242
1243 return !journal_exists && !wal_exists && !path_exists;
[email protected]8d2e39e2013-06-24 05:55:081244}
1245
[email protected]e5ffd0e42009-09-11 21:30:561246bool Connection::BeginTransaction() {
1247 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:331248 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:561249
1250 // When we're going to rollback, fail on this begin and don't actually
1251 // mark us as entering the nested transaction.
1252 return false;
1253 }
1254
1255 bool success = true;
1256 if (!transaction_nesting_) {
1257 needs_rollback_ = false;
1258
1259 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
shess58b8df82015-06-03 00:19:321260 RecordOneEvent(EVENT_BEGIN);
[email protected]eff1fa522011-12-12 23:50:591261 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:561262 return false;
1263 }
1264 transaction_nesting_++;
1265 return success;
1266}
1267
1268void Connection::RollbackTransaction() {
1269 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:381270 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561271 return;
1272 }
1273
1274 transaction_nesting_--;
1275
1276 if (transaction_nesting_ > 0) {
1277 // Mark the outermost transaction as needing rollback.
1278 needs_rollback_ = true;
1279 return;
1280 }
1281
1282 DoRollback();
1283}
1284
1285bool Connection::CommitTransaction() {
1286 if (!transaction_nesting_) {
shess90244e12015-11-09 22:08:181287 DLOG_IF(FATAL, !poisoned_) << "Committing a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:561288 return false;
1289 }
1290 transaction_nesting_--;
1291
1292 if (transaction_nesting_ > 0) {
1293 // Mark any nested transactions as failing after we've already got one.
1294 return !needs_rollback_;
1295 }
1296
1297 if (needs_rollback_) {
1298 DoRollback();
1299 return false;
1300 }
1301
1302 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
shess58b8df82015-06-03 00:19:321303
1304 // Collect the commit time manually, sql::Statement would register it as query
1305 // time only.
1306 const base::TimeTicks before = Now();
1307 bool ret = commit.RunWithoutTimers();
1308 const base::TimeDelta delta = Now() - before;
1309
1310 RecordCommitTime(delta);
1311 RecordOneEvent(EVENT_COMMIT);
1312
shess7dbd4dee2015-10-06 17:39:161313 // Release dirty cache pages after the transaction closes.
1314 ReleaseCacheMemoryIfNeeded(false);
1315
shess58b8df82015-06-03 00:19:321316 return ret;
[email protected]e5ffd0e42009-09-11 21:30:561317}
1318
[email protected]8d409412013-07-19 18:25:301319void Connection::RollbackAllTransactions() {
1320 if (transaction_nesting_ > 0) {
1321 transaction_nesting_ = 0;
1322 DoRollback();
1323 }
1324}
1325
1326bool Connection::AttachDatabase(const base::FilePath& other_db_path,
1327 const char* attachment_point) {
1328 DCHECK(ValidAttachmentPoint(attachment_point));
1329
1330 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
1331#if OS_WIN
1332 s.BindString16(0, other_db_path.value());
1333#else
1334 s.BindString(0, other_db_path.value());
1335#endif
1336 s.BindString(1, attachment_point);
1337 return s.Run();
1338}
1339
1340bool Connection::DetachDatabase(const char* attachment_point) {
1341 DCHECK(ValidAttachmentPoint(attachment_point));
1342
1343 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
1344 s.BindString(0, attachment_point);
1345 return s.Run();
1346}
1347
shess58b8df82015-06-03 00:19:321348// TODO(shess): Consider changing this to execute exactly one statement. If a
1349// caller wishes to execute multiple statements, that should be explicit, and
1350// perhaps tucked into an explicit transaction with rollback in case of error.
[email protected]eff1fa522011-12-12 23:50:591351int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501352 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381353 if (!db_) {
1354 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1355 return SQLITE_ERROR;
1356 }
shess58b8df82015-06-03 00:19:321357 DCHECK(sql);
1358
1359 RecordOneEvent(EVENT_EXECUTE);
1360 int rc = SQLITE_OK;
1361 while ((rc == SQLITE_OK) && *sql) {
1362 sqlite3_stmt *stmt = NULL;
1363 const char *leftover_sql;
1364
1365 const base::TimeTicks before = Now();
1366 rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, &leftover_sql);
1367 sql = leftover_sql;
1368
1369 // Stop if an error is encountered.
1370 if (rc != SQLITE_OK)
1371 break;
1372
1373 // This happens if |sql| originally only contained comments or whitespace.
1374 // TODO(shess): Audit to see if this can become a DCHECK(). Having
1375 // extraneous comments and whitespace in the SQL statements increases
1376 // runtime cost and can easily be shifted out to the C++ layer.
1377 if (!stmt)
1378 continue;
1379
1380 // Save for use after statement is finalized.
1381 const bool read_only = !!sqlite3_stmt_readonly(stmt);
1382
1383 RecordOneEvent(Connection::EVENT_STATEMENT_RUN);
1384 while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
1385 // TODO(shess): Audit to see if this can become a DCHECK. I think PRAGMA
1386 // is the only legitimate case for this.
1387 RecordOneEvent(Connection::EVENT_STATEMENT_ROWS);
1388 }
1389
1390 // sqlite3_finalize() returns SQLITE_OK if the most recent sqlite3_step()
1391 // returned SQLITE_DONE or SQLITE_ROW, otherwise the error code.
1392 rc = sqlite3_finalize(stmt);
1393 if (rc == SQLITE_OK)
1394 RecordOneEvent(Connection::EVENT_STATEMENT_SUCCESS);
1395
1396 // sqlite3_exec() does this, presumably to avoid spinning the parser for
1397 // trailing whitespace.
1398 // TODO(shess): Audit to see if this can become a DCHECK.
brettwb3413062015-06-24 00:39:021399 while (base::IsAsciiWhitespace(*sql)) {
shess58b8df82015-06-03 00:19:321400 sql++;
1401 }
1402
1403 const base::TimeDelta delta = Now() - before;
1404 RecordTimeAndChanges(delta, read_only);
1405 }
shess7dbd4dee2015-10-06 17:39:161406
1407 // Most calls to Execute() modify the database. The main exceptions would be
1408 // calls such as CREATE TABLE IF NOT EXISTS which could modify the database
1409 // but sometimes don't.
1410 ReleaseCacheMemoryIfNeeded(true);
1411
shess58b8df82015-06-03 00:19:321412 return rc;
[email protected]eff1fa522011-12-12 23:50:591413}
1414
1415bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:381416 if (!db_) {
1417 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1418 return false;
1419 }
1420
[email protected]eff1fa522011-12-12 23:50:591421 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:001422 if (error != SQLITE_OK)
[email protected]2f496b42013-09-26 18:36:581423 error = OnSqliteError(error, NULL, sql);
[email protected]473ad792012-11-10 00:55:001424
[email protected]28fe0ff2012-02-25 00:40:331425 // This needs to be a FATAL log because the error case of arriving here is
1426 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:101427 // a change alters the schema but not all queries adjust. This can happen
1428 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:591429 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:331430 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:591431 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:561432}
1433
[email protected]5b96f3772010-09-28 16:30:571434bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:381435 if (!db_) {
1436 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:571437 return false;
[email protected]41a97c812013-02-07 02:35:381438 }
[email protected]5b96f3772010-09-28 16:30:571439
1440 ScopedBusyTimeout busy_timeout(db_);
1441 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:591442 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:571443}
1444
[email protected]e5ffd0e42009-09-11 21:30:561445bool Connection::HasCachedStatement(const StatementID& id) const {
1446 return statement_cache_.find(id) != statement_cache_.end();
1447}
1448
1449scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
1450 const StatementID& id,
1451 const char* sql) {
1452 CachedStatementMap::iterator i = statement_cache_.find(id);
1453 if (i != statement_cache_.end()) {
1454 // Statement is in the cache. It should still be active (we're the only
1455 // one invalidating cached statements, and we'll remove it from the cache
1456 // if we do that. Make sure we reset it before giving out the cached one in
1457 // case it still has some stuff bound.
1458 DCHECK(i->second->is_valid());
1459 sqlite3_reset(i->second->stmt());
1460 return i->second;
1461 }
1462
1463 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
1464 if (statement->is_valid())
1465 statement_cache_[id] = statement; // Only cache valid statements.
1466 return statement;
1467}
1468
1469scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
1470 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501471 AssertIOAllowed();
1472
[email protected]41a97c812013-02-07 02:35:381473 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:561474 if (!db_)
[email protected]41a97c812013-02-07 02:35:381475 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:561476
1477 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:001478 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1479 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:591480 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061481 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021482 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:001483
1484 // It could also be database corruption.
[email protected]2f496b42013-09-26 18:36:581485 OnSqliteError(rc, NULL, sql);
[email protected]41a97c812013-02-07 02:35:381486 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:561487 }
[email protected]41a97c812013-02-07 02:35:381488 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:561489}
1490
shessf7e988f2015-11-13 00:41:061491// TODO(shess): Unify this with GetUniqueStatement(). The only difference that
1492// seems legitimate is not passing |this| to StatementRef.
[email protected]2eec0a22012-07-24 01:59:581493scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
1494 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:381495 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:581496 if (!db_)
[email protected]41a97c812013-02-07 02:35:381497 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:581498
1499 sqlite3_stmt* stmt = NULL;
1500 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
1501 if (rc != SQLITE_OK) {
1502 // This is evidence of a syntax error in the incoming SQL.
shessf7e988f2015-11-13 00:41:061503 if (!ShouldIgnoreSqliteCompileError(rc))
shess193bfb622015-04-10 22:30:021504 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:381505 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:581506 }
[email protected]41a97c812013-02-07 02:35:381507 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:581508}
1509
[email protected]92cd00a2013-08-16 11:09:581510std::string Connection::GetSchema() const {
1511 // The ORDER BY should not be necessary, but relying on organic
1512 // order for something like this is questionable.
1513 const char* kSql =
1514 "SELECT type, name, tbl_name, sql "
1515 "FROM sqlite_master ORDER BY 1, 2, 3, 4";
1516 Statement statement(GetUntrackedStatement(kSql));
1517
1518 std::string schema;
1519 while (statement.Step()) {
1520 schema += statement.ColumnString(0);
1521 schema += '|';
1522 schema += statement.ColumnString(1);
1523 schema += '|';
1524 schema += statement.ColumnString(2);
1525 schema += '|';
1526 schema += statement.ColumnString(3);
1527 schema += '\n';
1528 }
1529
1530 return schema;
1531}
1532
[email protected]eff1fa522011-12-12 23:50:591533bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:501534 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:381535 if (!db_) {
1536 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
1537 return false;
1538 }
1539
[email protected]eff1fa522011-12-12 23:50:591540 sqlite3_stmt* stmt = NULL;
1541 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
1542 return false;
1543
1544 sqlite3_finalize(stmt);
1545 return true;
1546}
1547
[email protected]1ed78a32009-09-15 20:24:171548bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:531549 return DoesTableOrIndexExist(table_name, "table");
1550}
1551
1552bool Connection::DoesIndexExist(const char* index_name) const {
1553 return DoesTableOrIndexExist(index_name, "index");
1554}
1555
1556bool Connection::DoesTableOrIndexExist(
1557 const char* name, const char* type) const {
shess92a2ab12015-04-09 01:59:471558 const char* kSql =
1559 "SELECT name FROM sqlite_master WHERE type=? AND name=? COLLATE NOCASE";
[email protected]2eec0a22012-07-24 01:59:581560 Statement statement(GetUntrackedStatement(kSql));
shess92a2ab12015-04-09 01:59:471561
1562 // This can happen if the database is corrupt and the error is being ignored
1563 // for testing purposes.
1564 if (!statement.is_valid())
1565 return false;
1566
[email protected]e2cadec82011-12-13 02:00:531567 statement.BindString(0, type);
1568 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:331569
[email protected]e5ffd0e42009-09-11 21:30:561570 return statement.Step(); // Table exists if any row was returned.
1571}
1572
1573bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:171574 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:561575 std::string sql("PRAGMA TABLE_INFO(");
1576 sql.append(table_name);
1577 sql.append(")");
1578
[email protected]2eec0a22012-07-24 01:59:581579 Statement statement(GetUntrackedStatement(sql.c_str()));
shess92a2ab12015-04-09 01:59:471580
1581 // This can happen if the database is corrupt and the error is being ignored
1582 // for testing purposes.
1583 if (!statement.is_valid())
1584 return false;
1585
[email protected]e5ffd0e42009-09-11 21:30:561586 while (statement.Step()) {
brettw8a800902015-07-10 18:28:331587 if (base::EqualsCaseInsensitiveASCII(statement.ColumnString(1),
1588 column_name))
[email protected]e5ffd0e42009-09-11 21:30:561589 return true;
1590 }
1591 return false;
1592}
1593
tfarina720d4f32015-05-11 22:31:261594int64_t Connection::GetLastInsertRowId() const {
[email protected]e5ffd0e42009-09-11 21:30:561595 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381596 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:561597 return 0;
1598 }
1599 return sqlite3_last_insert_rowid(db_);
1600}
1601
[email protected]1ed78a32009-09-15 20:24:171602int Connection::GetLastChangeCount() const {
1603 if (!db_) {
[email protected]41a97c812013-02-07 02:35:381604 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:171605 return 0;
1606 }
1607 return sqlite3_changes(db_);
1608}
1609
[email protected]e5ffd0e42009-09-11 21:30:561610int Connection::GetErrorCode() const {
1611 if (!db_)
1612 return SQLITE_ERROR;
1613 return sqlite3_errcode(db_);
1614}
1615
[email protected]767718e52010-09-21 23:18:491616int Connection::GetLastErrno() const {
1617 if (!db_)
1618 return -1;
1619
1620 int err = 0;
1621 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
1622 return -2;
1623
1624 return err;
1625}
1626
[email protected]e5ffd0e42009-09-11 21:30:561627const char* Connection::GetErrorMessage() const {
1628 if (!db_)
1629 return "sql::Connection has no connection.";
1630 return sqlite3_errmsg(db_);
1631}
1632
[email protected]fed734a2013-07-17 04:45:131633bool Connection::OpenInternal(const std::string& file_name,
1634 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:501635 AssertIOAllowed();
1636
[email protected]9cfbc922009-11-17 20:13:171637 if (db_) {
[email protected]eff1fa522011-12-12 23:50:591638 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:171639 return false;
1640 }
1641
[email protected]a7ec1292013-07-22 22:02:181642 // Make sure sqlite3_initialize() is called before anything else.
1643 InitializeSqlite();
1644
shess58b8df82015-06-03 00:19:321645 // Setup the stats histograms immediately rather than allocating lazily.
1646 // Connections which won't exercise all of these probably shouldn't exist.
1647 if (!histogram_tag_.empty()) {
1648 stats_histogram_ =
1649 base::LinearHistogram::FactoryGet(
1650 "Sqlite.Stats." + histogram_tag_,
1651 1, EVENT_MAX_VALUE, EVENT_MAX_VALUE + 1,
1652 base::HistogramBase::kUmaTargetedHistogramFlag);
1653
1654 // The timer setup matches UMA_HISTOGRAM_MEDIUM_TIMES(). 3 minutes is an
1655 // unreasonable time for any single operation, so there is not much value to
1656 // knowing if it was 3 minutes or 5 minutes. In reality at that point
1657 // things are entirely busted.
1658 commit_time_histogram_ =
1659 GetMediumTimeHistogram("Sqlite.CommitTime." + histogram_tag_);
1660
1661 autocommit_time_histogram_ =
1662 GetMediumTimeHistogram("Sqlite.AutoCommitTime." + histogram_tag_);
1663
1664 update_time_histogram_ =
1665 GetMediumTimeHistogram("Sqlite.UpdateTime." + histogram_tag_);
1666
1667 query_time_histogram_ =
1668 GetMediumTimeHistogram("Sqlite.QueryTime." + histogram_tag_);
1669 }
1670
[email protected]41a97c812013-02-07 02:35:381671 // If |poisoned_| is set, it means an error handler called
1672 // RazeAndClose(). Until regular Close() is called, the caller
1673 // should be treating the database as open, but is_open() currently
1674 // only considers the sqlite3 handle's state.
1675 // TODO(shess): Revise is_open() to consider poisoned_, and review
1676 // to see if any non-testing code even depends on it.
1677 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:161678 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:381679
[email protected]765b44502009-10-02 05:01:421680 int err = sqlite3_open(file_name.c_str(), &db_);
1681 if (err != SQLITE_OK) {
[email protected]73fb8d52013-07-24 05:04:281682 // Extended error codes cannot be enabled until a handle is
1683 // available, fetch manually.
1684 err = sqlite3_extended_errcode(db_);
1685
[email protected]bd2ccdb4a2012-12-07 22:14:501686 // Histogram failures specific to initial open for debugging
1687 // purposes.
[email protected]73fb8d52013-07-24 05:04:281688 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenFailure", err);
[email protected]bd2ccdb4a2012-12-07 22:14:501689
[email protected]2f496b42013-09-26 18:36:581690 OnSqliteError(err, NULL, "-- sqlite3_open()");
[email protected]fed734a2013-07-17 04:45:131691 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:291692 Close();
[email protected]fed734a2013-07-17 04:45:131693
1694 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1695 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:421696 return false;
1697 }
1698
[email protected]81a2a602013-07-17 19:10:361699 // TODO(shess): OS_WIN support?
1700#if defined(OS_POSIX)
1701 if (restrict_to_user_) {
1702 DCHECK_NE(file_name, std::string(":memory"));
1703 base::FilePath file_path(file_name);
1704 int mode = 0;
1705 // TODO(shess): Arguably, failure to retrieve and change
1706 // permissions should be fatal if the file exists.
[email protected]b264eab2013-11-27 23:22:081707 if (base::GetPosixFilePermissions(file_path, &mode)) {
1708 mode &= base::FILE_PERMISSION_USER_MASK;
1709 base::SetPosixFilePermissions(file_path, mode);
[email protected]81a2a602013-07-17 19:10:361710
1711 // SQLite sets the permissions on these files from the main
1712 // database on create. Set them here in case they already exist
1713 // at this point. Failure to set these permissions should not
1714 // be fatal unless the file doesn't exist.
1715 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
1716 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
[email protected]b264eab2013-11-27 23:22:081717 base::SetPosixFilePermissions(journal_path, mode);
1718 base::SetPosixFilePermissions(wal_path, mode);
[email protected]81a2a602013-07-17 19:10:361719 }
1720 }
1721#endif // defined(OS_POSIX)
1722
[email protected]affa2da2013-06-06 22:20:341723 // SQLite uses a lookaside buffer to improve performance of small mallocs.
1724 // Chromium already depends on small mallocs being efficient, so we disable
1725 // this to avoid the extra memory overhead.
1726 // This must be called immediatly after opening the database before any SQL
1727 // statements are run.
1728 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
1729
[email protected]73fb8d52013-07-24 05:04:281730 // Enable extended result codes to provide more color on I/O errors.
1731 // Not having extended result codes is not a fatal problem, as
1732 // Chromium code does not attempt to handle I/O errors anyhow. The
1733 // current implementation always returns SQLITE_OK, the DCHECK is to
1734 // quickly notify someone if SQLite changes.
1735 err = sqlite3_extended_result_codes(db_, 1);
1736 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
1737
[email protected]bd2ccdb4a2012-12-07 22:14:501738 // sqlite3_open() does not actually read the database file (unless a
1739 // hot journal is found). Successfully executing this pragma on an
1740 // existing database requires a valid header on page 1.
1741 // TODO(shess): For now, just probing to see what the lay of the
1742 // land is. If it's mostly SQLITE_NOTADB, then the database should
1743 // be razed.
1744 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
1745 if (err != SQLITE_OK)
[email protected]73fb8d52013-07-24 05:04:281746 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.OpenProbeFailure", err);
[email protected]658f8332010-09-18 04:40:431747
[email protected]2e1cee762013-07-09 14:40:001748#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
1749 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
1750 // REGEXP support. Add it in dynamically.
1751 err = sqlite3IcuInit(db_);
1752 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
1753#endif // OS_IOS && USE_SYSTEM_SQLITE
1754
[email protected]5b96f3772010-09-28 16:30:571755 // If indicated, lock up the database before doing anything else, so
1756 // that the following code doesn't have to deal with locking.
1757 // TODO(shess): This code is brittle. Find the cases where code
1758 // doesn't request |exclusive_locking_| and audit that it does the
1759 // right thing with SQLITE_BUSY, and that it doesn't make
1760 // assumptions about who might change things in the database.
1761 // http://crbug.com/56559
1762 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:101763 // TODO(shess): This should probably be a failure. Code which
1764 // requests exclusive locking but doesn't get it is almost certain
1765 // to be ill-tested.
1766 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:571767 }
1768
[email protected]4e179ba62012-03-17 16:06:471769 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1770 // DELETE (default) - delete -journal file to commit.
1771 // TRUNCATE - truncate -journal file to commit.
1772 // PERSIST - zero out header of -journal file to commit.
shess2c21ecf2015-06-02 01:31:091773 // TRUNCATE should be faster than DELETE because it won't need directory
1774 // changes for each transaction. PERSIST may break the spirit of using
1775 // secure_delete.
1776 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
[email protected]4e179ba62012-03-17 16:06:471777
[email protected]c68ce172011-11-24 22:30:271778 const base::TimeDelta kBusyTimeout =
1779 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1780
[email protected]765b44502009-10-02 05:01:421781 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:571782 // Enforce SQLite restrictions on |page_size_|.
1783 DCHECK(!(page_size_ & (page_size_ - 1)))
1784 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:241785 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:571786 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:041787 const std::string sql =
1788 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:101789 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421790 }
1791
1792 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:041793 const std::string sql =
1794 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:101795 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:421796 }
1797
[email protected]6e0b1442011-08-09 23:23:581798 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:131799 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:581800 Close();
[email protected]fed734a2013-07-17 04:45:131801 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1802 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:581803 return false;
1804 }
1805
shess5dac334f2015-11-05 20:47:421806 // Set a reasonable chunk size for larger files. This reduces churn from
1807 // remapping memory on size changes. It also reduces filesystem
1808 // fragmentation.
1809 // TODO(shess): It may make sense to have this be hinted by the client.
1810 // Database sizes seem to be bimodal, some clients have consistently small
1811 // databases (<20k) while other clients have a broad distribution of sizes
1812 // (hundreds of kilobytes to many megabytes).
1813 sqlite3_file* file = NULL;
1814 sqlite3_int64 db_size = 0;
1815 int rc = GetSqlite3FileAndSize(db_, &file, &db_size);
1816 if (rc == SQLITE_OK && db_size > 16 * 1024) {
1817 int chunk_size = 4 * 1024;
1818 if (db_size > 128 * 1024)
1819 chunk_size = 32 * 1024;
1820 sqlite3_file_control(db_, NULL, SQLITE_FCNTL_CHUNK_SIZE, &chunk_size);
1821 }
1822
shess2f3a814b2015-11-05 18:11:101823 // Enable memory-mapped access. The explicit-disable case is because SQLite
shessd90aeea82015-11-13 02:24:311824 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1825 // safe range to memory-map based on past regular I/O. This value will be
1826 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1827 // 64-bit platforms.
1828 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1829 std::string mmap_sql =
1830 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1831 ignore_result(Execute(mmap_sql.c_str()));
shess2f3a814b2015-11-05 18:11:101832
1833 // Determine if memory-mapping has actually been enabled. The Execute() above
1834 // can succeed without changing the amount mapped.
1835 mmap_enabled_ = false;
1836 {
1837 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1838 if (s.Step() && s.ColumnInt64(0) > 0)
1839 mmap_enabled_ = true;
1840 }
1841
ssid3be5b1ec2016-01-13 14:21:571842 DCHECK(!memory_dump_provider_);
1843 memory_dump_provider_.reset(
1844 new ConnectionMemoryDumpProvider(db_, histogram_tag_));
1845 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
1846 memory_dump_provider_.get(), "sql::Connection", nullptr);
1847
[email protected]765b44502009-10-02 05:01:421848 return true;
1849}
1850
[email protected]e5ffd0e42009-09-11 21:30:561851void Connection::DoRollback() {
1852 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
shess58b8df82015-06-03 00:19:321853
1854 // Collect the rollback time manually, sql::Statement would register it as
1855 // query time only.
1856 const base::TimeTicks before = Now();
1857 rollback.RunWithoutTimers();
1858 const base::TimeDelta delta = Now() - before;
1859
1860 RecordUpdateTime(delta);
1861 RecordOneEvent(EVENT_ROLLBACK);
1862
shess7dbd4dee2015-10-06 17:39:161863 // The cache may have been accumulating dirty pages for commit. Note that in
1864 // some cases sql::Transaction can fire rollback after a database is closed.
1865 if (is_open())
1866 ReleaseCacheMemoryIfNeeded(false);
1867
[email protected]44ad7d902012-03-23 00:09:051868 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:561869}
1870
1871void Connection::StatementRefCreated(StatementRef* ref) {
1872 DCHECK(open_statements_.find(ref) == open_statements_.end());
1873 open_statements_.insert(ref);
1874}
1875
1876void Connection::StatementRefDeleted(StatementRef* ref) {
1877 StatementRefSet::iterator i = open_statements_.find(ref);
1878 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:591879 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:561880 else
1881 open_statements_.erase(i);
1882}
1883
shess58b8df82015-06-03 00:19:321884void Connection::set_histogram_tag(const std::string& tag) {
1885 DCHECK(!is_open());
1886 histogram_tag_ = tag;
1887}
1888
[email protected]210ce0af2013-05-15 09:10:391889void Connection::AddTaggedHistogram(const std::string& name,
1890 size_t sample) const {
1891 if (histogram_tag_.empty())
1892 return;
1893
1894 // TODO(shess): The histogram macros create a bit of static storage
1895 // for caching the histogram object. This code shouldn't execute
1896 // often enough for such caching to be crucial. If it becomes an
1897 // issue, the object could be cached alongside histogram_prefix_.
1898 std::string full_histogram_name = name + "." + histogram_tag_;
1899 base::HistogramBase* histogram =
1900 base::SparseHistogram::FactoryGet(
1901 full_histogram_name,
1902 base::HistogramBase::kUmaTargetedHistogramFlag);
1903 if (histogram)
1904 histogram->Add(sample);
1905}
1906
[email protected]2f496b42013-09-26 18:36:581907int Connection::OnSqliteError(int err, sql::Statement *stmt, const char* sql) {
[email protected]210ce0af2013-05-15 09:10:391908 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
1909 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:141910
1911 // Always log the error.
[email protected]2f496b42013-09-26 18:36:581912 if (!sql && stmt)
1913 sql = stmt->GetSQLStatement();
1914 if (!sql)
1915 sql = "-- unknown";
shessf7e988f2015-11-13 00:41:061916
1917 std::string id = histogram_tag_;
1918 if (id.empty())
1919 id = DbPath().BaseName().AsUTF8Unsafe();
1920 LOG(ERROR) << id << " sqlite error " << err
[email protected]c088e3a32013-01-03 23:59:141921 << ", errno " << GetLastErrno()
[email protected]2f496b42013-09-26 18:36:581922 << ": " << GetErrorMessage()
1923 << ", sql: " << sql;
[email protected]c088e3a32013-01-03 23:59:141924
[email protected]c3881b372013-05-17 08:39:461925 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561926 // Fire from a copy of the callback in case of reentry into
1927 // re/set_error_callback().
1928 // TODO(shess): <http://crbug.com/254584>
1929 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461930 return err;
1931 }
1932
[email protected]faa604e2009-09-25 22:38:591933 // The default handling is to assert on debug and to ignore on release.
[email protected]74cdede2013-09-25 05:39:571934 if (!ShouldIgnoreSqliteError(err))
[email protected]4350e322013-06-18 22:18:101935 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591936 return err;
1937}
1938
[email protected]579446c2013-12-16 18:36:521939bool Connection::FullIntegrityCheck(std::vector<std::string>* messages) {
1940 return IntegrityCheckHelper("PRAGMA integrity_check", messages);
1941}
1942
1943bool Connection::QuickIntegrityCheck() {
1944 std::vector<std::string> messages;
1945 if (!IntegrityCheckHelper("PRAGMA quick_check", &messages))
1946 return false;
1947 return messages.size() == 1 && messages[0] == "ok";
1948}
1949
[email protected]80abf152013-05-22 12:42:421950// TODO(shess): Allow specifying maximum results (default 100 lines).
[email protected]579446c2013-12-16 18:36:521951bool Connection::IntegrityCheckHelper(
1952 const char* pragma_sql,
1953 std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421954 messages->clear();
1955
[email protected]4658e2a02013-06-06 23:05:001956 // This has the side effect of setting SQLITE_RecoveryMode, which
1957 // allows SQLite to process through certain cases of corruption.
1958 // Failing to set this pragma probably means that the database is
1959 // beyond recovery.
1960 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1961 if (!Execute(kWritableSchema))
1962 return false;
1963
1964 bool ret = false;
1965 {
[email protected]579446c2013-12-16 18:36:521966 sql::Statement stmt(GetUniqueStatement(pragma_sql));
[email protected]4658e2a02013-06-06 23:05:001967
1968 // The pragma appears to return all results (up to 100 by default)
1969 // as a single string. This doesn't appear to be an API contract,
1970 // it could return separate lines, so loop _and_ split.
1971 while (stmt.Step()) {
1972 std::string result(stmt.ColumnString(0));
brettw83dc1612015-08-12 07:31:181973 *messages = base::SplitString(result, "\n", base::TRIM_WHITESPACE,
1974 base::SPLIT_WANT_ALL);
[email protected]4658e2a02013-06-06 23:05:001975 }
1976 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421977 }
[email protected]4658e2a02013-06-06 23:05:001978
1979 // Best effort to put things back as they were before.
1980 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1981 ignore_result(Execute(kNoWritableSchema));
1982
1983 return ret;
[email protected]80abf152013-05-22 12:42:421984}
1985
shess58b8df82015-06-03 00:19:321986base::TimeTicks TimeSource::Now() {
1987 return base::TimeTicks::Now();
1988}
1989
[email protected]e5ffd0e42009-09-11 21:30:561990} // namespace sql