blob: c10f5a77ce8c484d16462cc74635882ee25bc17a [file] [log] [blame]
[email protected]64021042012-02-10 20:02:291// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]e5ffd0e42009-09-11 21:30:562// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f0a54b22011-07-19 18:40:215#include "sql/connection.h"
[email protected]e5ffd0e42009-09-11 21:30:566
7#include <string.h>
8
[email protected]57999812013-02-24 05:40:529#include "base/files/file_path.h"
[email protected]348ac8f52013-05-21 03:27:0210#include "base/file_util.h"
[email protected]a7ec1292013-07-22 22:02:1811#include "base/lazy_instance.h"
[email protected]e5ffd0e42009-09-11 21:30:5612#include "base/logging.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5013#include "base/metrics/histogram.h"
[email protected]210ce0af2013-05-15 09:10:3914#include "base/metrics/sparse_histogram.h"
[email protected]80abf152013-05-22 12:42:4215#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1916#include "base/strings/string_util.h"
17#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4518#include "base/strings/utf_string_conversions.h"
[email protected]a7ec1292013-07-22 22:02:1819#include "base/synchronization/lock.h"
[email protected]f0a54b22011-07-19 18:40:2120#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0321#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5622
[email protected]2e1cee762013-07-09 14:40:0023#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
24#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
25#endif
26
[email protected]5b96f3772010-09-28 16:30:5727namespace {
28
29// Spin for up to a second waiting for the lock to clear when setting
30// up the database.
31// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2732const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5733
34class ScopedBusyTimeout {
35 public:
36 explicit ScopedBusyTimeout(sqlite3* db)
37 : db_(db) {
38 }
39 ~ScopedBusyTimeout() {
40 sqlite3_busy_timeout(db_, 0);
41 }
42
43 int SetTimeout(base::TimeDelta timeout) {
44 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
45 return sqlite3_busy_timeout(db_,
46 static_cast<int>(timeout.InMilliseconds()));
47 }
48
49 private:
50 sqlite3* db_;
51};
52
[email protected]6d42f152012-11-10 00:38:2453// Helper to "safely" enable writable_schema. No error checking
54// because it is reasonable to just forge ahead in case of an error.
55// If turning it on fails, then most likely nothing will work, whereas
56// if turning it off fails, it only matters if some code attempts to
57// continue working with the database and tries to modify the
58// sqlite_master table (none of our code does this).
59class ScopedWritableSchema {
60 public:
61 explicit ScopedWritableSchema(sqlite3* db)
62 : db_(db) {
63 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
64 }
65 ~ScopedWritableSchema() {
66 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
67 }
68
69 private:
70 sqlite3* db_;
71};
72
[email protected]7bae5742013-07-10 20:46:1673// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
74// SQLite error code from running the backup step.
75int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
76 DCHECK_NE(src, dst);
77 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
78 if (!backup) {
79 // Since this call only sets things up, this indicates a gross
80 // error in SQLite.
81 DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
82 return sqlite3_errcode(dst);
83 }
84
85 // -1 backs up the entire database.
86 int rc = sqlite3_backup_step(backup, -1);
87 int pages = sqlite3_backup_pagecount(backup);
88 sqlite3_backup_finish(backup);
89
90 // If successful, exactly one page should have been backed up. If
91 // this breaks, check this function to make sure assumptions aren't
92 // being broken.
93 if (rc == SQLITE_DONE)
94 DCHECK_EQ(pages, 1);
95
96 return rc;
97}
98
[email protected]8d409412013-07-19 18:25:3099// Be very strict on attachment point. SQLite can handle a much wider
100// character set with appropriate quoting, but Chromium code should
101// just use clean names to start with.
102bool ValidAttachmentPoint(const char* attachment_point) {
103 for (size_t i = 0; attachment_point[i]; ++i) {
104 if (!((attachment_point[i] >= '0' && attachment_point[i] <= '9') ||
105 (attachment_point[i] >= 'a' && attachment_point[i] <= 'z') ||
106 (attachment_point[i] >= 'A' && attachment_point[i] <= 'Z') ||
107 attachment_point[i] == '_')) {
108 return false;
109 }
110 }
111 return true;
112}
113
[email protected]a7ec1292013-07-22 22:02:18114// SQLite automatically calls sqlite3_initialize() lazily, but
115// sqlite3_initialize() uses double-checked locking and thus can have
116// data races.
117//
118// TODO(shess): Another alternative would be to have
119// sqlite3_initialize() called as part of process bring-up. If this
120// is changed, remove the dynamic_annotations dependency in sql.gyp.
121base::LazyInstance<base::Lock>::Leaky
122 g_sqlite_init_lock = LAZY_INSTANCE_INITIALIZER;
123void InitializeSqlite() {
124 base::AutoLock lock(g_sqlite_init_lock.Get());
125 sqlite3_initialize();
126}
127
[email protected]5b96f3772010-09-28 16:30:57128} // namespace
129
[email protected]e5ffd0e42009-09-11 21:30:56130namespace sql {
131
[email protected]4350e322013-06-18 22:18:10132// static
133Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL;
134
135// static
136bool Connection::ShouldIgnore(int error) {
137 if (!current_ignorer_cb_)
138 return false;
139 return current_ignorer_cb_->Run(error);
140}
141
142// static
143void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
144 CHECK(current_ignorer_cb_ == NULL);
145 current_ignorer_cb_ = cb;
146}
147
148// static
149void Connection::ResetErrorIgnorer() {
150 CHECK(current_ignorer_cb_);
151 current_ignorer_cb_ = NULL;
152}
153
[email protected]e5ffd0e42009-09-11 21:30:56154bool StatementID::operator<(const StatementID& other) const {
155 if (number_ != other.number_)
156 return number_ < other.number_;
157 return strcmp(str_, other.str_) < 0;
158}
159
[email protected]e5ffd0e42009-09-11 21:30:56160Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38161 sqlite3_stmt* stmt,
162 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56163 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38164 stmt_(stmt),
165 was_valid_(was_valid) {
166 if (connection)
167 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56168}
169
170Connection::StatementRef::~StatementRef() {
171 if (connection_)
172 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38173 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56174}
175
[email protected]41a97c812013-02-07 02:35:38176void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56177 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50178 // Call to AssertIOAllowed() cannot go at the beginning of the function
179 // because Close() is called unconditionally from destructor to clean
180 // connection_. And if this is inactive statement this won't cause any
181 // disk access and destructor most probably will be called on thread
182 // not allowing disk access.
183 // TODO([email protected]): This should move to the beginning
184 // of the function. http://crbug.com/136655.
185 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56186 sqlite3_finalize(stmt_);
187 stmt_ = NULL;
188 }
189 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38190
191 // Forced close is expected to happen from a statement error
192 // handler. In that case maintain the sense of |was_valid_| which
193 // previously held for this ref.
194 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56195}
196
197Connection::Connection()
198 : db_(NULL),
199 page_size_(0),
200 cache_size_(0),
201 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36202 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56203 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50204 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16205 in_memory_(false),
[email protected]526b4662013-06-14 04:09:12206 poisoned_(false) {
207}
[email protected]e5ffd0e42009-09-11 21:30:56208
209Connection::~Connection() {
210 Close();
211}
212
[email protected]a3ef4832013-02-02 05:12:33213bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02214 if (!histogram_tag_.empty()) {
215 int64 size_64 = 0;
216 if (file_util::GetFileSize(path, &size_64)) {
217 size_t sample = static_cast<size_t>(size_64 / 1024);
218 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
219 base::HistogramBase* histogram =
220 base::Histogram::FactoryGet(
221 full_histogram_name, 1, 1000000, 50,
222 base::HistogramBase::kUmaTargetedHistogramFlag);
223 if (histogram)
224 histogram->Add(sample);
225 }
226 }
227
[email protected]e5ffd0e42009-09-11 21:30:56228#if defined(OS_WIN)
[email protected]fed734a2013-07-17 04:45:13229 return OpenInternal(WideToUTF8(path.value()), RETRY_ON_POISON);
[email protected]e5ffd0e42009-09-11 21:30:56230#elif defined(OS_POSIX)
[email protected]fed734a2013-07-17 04:45:13231 return OpenInternal(path.value(), RETRY_ON_POISON);
[email protected]e5ffd0e42009-09-11 21:30:56232#endif
[email protected]765b44502009-10-02 05:01:42233}
[email protected]e5ffd0e42009-09-11 21:30:56234
[email protected]765b44502009-10-02 05:01:42235bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50236 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13237 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56238}
239
[email protected]8d409412013-07-19 18:25:30240bool Connection::OpenTemporary() {
241 return OpenInternal("", NO_RETRY);
242}
243
[email protected]41a97c812013-02-07 02:35:38244void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47245 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
246 // will delete the -journal file. For ChromiumOS or other more
247 // embedded systems, this is probably not appropriate, whereas on
248 // desktop it might make some sense.
249
[email protected]4b350052012-02-24 20:40:48250 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48251
[email protected]41a97c812013-02-07 02:35:38252 // Release cached statements.
253 statement_cache_.clear();
254
255 // With cached statements released, in-use statements will remain.
256 // Closing the database while statements are in use is an API
257 // violation, except for forced close (which happens from within a
258 // statement's error handler).
259 DCHECK(forced || open_statements_.empty());
260
261 // Deactivate any outstanding statements so sqlite3_close() works.
262 for (StatementRefSet::iterator i = open_statements_.begin();
263 i != open_statements_.end(); ++i)
264 (*i)->Close(forced);
265 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48266
[email protected]e5ffd0e42009-09-11 21:30:56267 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50268 // Call to AssertIOAllowed() cannot go at the beginning of the function
269 // because Close() must be called from destructor to clean
270 // statement_cache_, it won't cause any disk access and it most probably
271 // will happen on thread not allowing disk access.
272 // TODO([email protected]): This should move to the beginning
273 // of the function. http://crbug.com/136655.
274 AssertIOAllowed();
[email protected]4b350052012-02-24 20:40:48275 // TODO(shess): Histogram for failure.
[email protected]e5ffd0e42009-09-11 21:30:56276 sqlite3_close(db_);
[email protected]e5ffd0e42009-09-11 21:30:56277 }
[email protected]fed734a2013-07-17 04:45:13278 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56279}
280
[email protected]41a97c812013-02-07 02:35:38281void Connection::Close() {
282 // If the database was already closed by RazeAndClose(), then no
283 // need to close again. Clear the |poisoned_| bit so that incorrect
284 // API calls are caught.
285 if (poisoned_) {
286 poisoned_ = false;
287 return;
288 }
289
290 CloseInternal(false);
291}
292
[email protected]e5ffd0e42009-09-11 21:30:56293void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50294 AssertIOAllowed();
295
[email protected]e5ffd0e42009-09-11 21:30:56296 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38297 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56298 return;
299 }
300
301 // A statement must be open for the preload command to work. If the meta
302 // table doesn't exist, it probably means this is a new database and there
303 // is nothing to preload (so it's OK we do nothing).
304 if (!DoesTableExist("meta"))
305 return;
306 Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
[email protected]eff1fa522011-12-12 23:50:59307 if (!dummy.Step())
[email protected]e5ffd0e42009-09-11 21:30:56308 return;
309
[email protected]4176eee4b2011-01-26 14:33:32310#if !defined(USE_SYSTEM_SQLITE)
311 // This function is only defined in Chromium's version of sqlite.
312 // Do not call it when using system sqlite.
[email protected]67361b32011-04-12 20:13:06313 sqlite3_preload(db_);
[email protected]4176eee4b2011-01-26 14:33:32314#endif
[email protected]e5ffd0e42009-09-11 21:30:56315}
316
[email protected]be7995f12013-07-18 18:49:14317void Connection::TrimMemory(bool aggressively) {
318 if (!db_)
319 return;
320
321 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
322 int original_cache_size;
323 {
324 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
325 if (!sql_get_original.Step()) {
326 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
327 return;
328 }
329 original_cache_size = sql_get_original.ColumnInt(0);
330 }
331 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
332
333 // Force sqlite to try to reduce page cache usage.
334 const std::string sql_shrink =
335 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
336 if (!Execute(sql_shrink.c_str()))
337 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
338
339 // Restore cache size.
340 const std::string sql_restore =
341 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
342 if (!Execute(sql_restore.c_str()))
343 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
344}
345
[email protected]8e0c01282012-04-06 19:36:49346// Create an in-memory database with the existing database's page
347// size, then backup that database over the existing database.
348bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50349 AssertIOAllowed();
350
[email protected]8e0c01282012-04-06 19:36:49351 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38352 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49353 return false;
354 }
355
356 if (transaction_nesting_ > 0) {
357 DLOG(FATAL) << "Cannot raze within a transaction";
358 return false;
359 }
360
361 sql::Connection null_db;
362 if (!null_db.OpenInMemory()) {
363 DLOG(FATAL) << "Unable to open in-memory database.";
364 return false;
365 }
366
[email protected]6d42f152012-11-10 00:38:24367 if (page_size_) {
368 // Enforce SQLite restrictions on |page_size_|.
369 DCHECK(!(page_size_ & (page_size_ - 1)))
370 << " page_size_ " << page_size_ << " is not a power of two.";
371 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
372 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04373 const std::string sql =
374 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:42375 if (!null_db.Execute(sql.c_str()))
376 return false;
377 }
378
[email protected]6d42f152012-11-10 00:38:24379#if defined(OS_ANDROID)
380 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
381 // in-memory databases do not respect this define.
382 // TODO(shess): Figure out a way to set this without using platform
383 // specific code. AFAICT from sqlite3.c, the only way to do it
384 // would be to create an actual filesystem database, which is
385 // unfortunate.
386 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
387 return false;
388#endif
[email protected]8e0c01282012-04-06 19:36:49389
390 // The page size doesn't take effect until a database has pages, and
391 // at this point the null database has none. Changing the schema
392 // version will create the first page. This will not affect the
393 // schema version in the resulting database, as SQLite's backup
394 // implementation propagates the schema version from the original
395 // connection to the new version of the database, incremented by one
396 // so that other readers see the schema change and act accordingly.
397 if (!null_db.Execute("PRAGMA schema_version = 1"))
398 return false;
399
[email protected]6d42f152012-11-10 00:38:24400 // SQLite tracks the expected number of database pages in the first
401 // page, and if it does not match the total retrieved from a
402 // filesystem call, treats the database as corrupt. This situation
403 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
404 // used to hint to SQLite to soldier on in that case, specifically
405 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
406 // sqlite3.c lockBtree().]
407 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
408 // page_size" can be used to query such a database.
409 ScopedWritableSchema writable_schema(db_);
410
[email protected]7bae5742013-07-10 20:46:16411 const char* kMain = "main";
412 int rc = BackupDatabase(null_db.db_, db_, kMain);
413 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:49414
415 // The destination database was locked.
416 if (rc == SQLITE_BUSY) {
417 return false;
418 }
419
[email protected]7bae5742013-07-10 20:46:16420 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
421 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
422 // isn't even big enough for one page. Either way, reach in and
423 // truncate it before trying again.
424 // TODO(shess): Maybe it would be worthwhile to just truncate from
425 // the get-go?
426 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
427 sqlite3_file* file = NULL;
428 rc = sqlite3_file_control(db_, "main", SQLITE_FCNTL_FILE_POINTER, &file);
429 if (rc != SQLITE_OK) {
430 DLOG(FATAL) << "Failure getting file handle.";
431 return false;
432 } else if (!file) {
433 DLOG(FATAL) << "File handle is empty.";
434 return false;
435 }
436
437 rc = file->pMethods->xTruncate(file, 0);
438 if (rc != SQLITE_OK) {
439 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
440 DLOG(FATAL) << "Failed to truncate file.";
441 return false;
442 }
443
444 rc = BackupDatabase(null_db.db_, db_, kMain);
445 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
446
447 if (rc != SQLITE_DONE) {
448 DLOG(FATAL) << "Failed retrying Raze().";
449 }
450 }
451
[email protected]8e0c01282012-04-06 19:36:49452 // The entire database should have been backed up.
453 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:16454 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:49455 DLOG(FATAL) << "Unable to copy entire null database.";
456 return false;
457 }
458
[email protected]8e0c01282012-04-06 19:36:49459 return true;
460}
461
462bool Connection::RazeWithTimout(base::TimeDelta timeout) {
463 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38464 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49465 return false;
466 }
467
468 ScopedBusyTimeout busy_timeout(db_);
469 busy_timeout.SetTimeout(timeout);
470 return Raze();
471}
472
[email protected]41a97c812013-02-07 02:35:38473bool Connection::RazeAndClose() {
474 if (!db_) {
475 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
476 return false;
477 }
478
479 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:30480 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:38481
482 bool result = Raze();
483
484 CloseInternal(true);
485
486 // Mark the database so that future API calls fail appropriately,
487 // but don't DCHECK (because after calling this function they are
488 // expected to fail).
489 poisoned_ = true;
490
491 return result;
492}
493
[email protected]8d409412013-07-19 18:25:30494void Connection::Poison() {
495 if (!db_) {
496 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
497 return;
498 }
499
500 RollbackAllTransactions();
501 CloseInternal(true);
502
503 // Mark the database so that future API calls fail appropriately,
504 // but don't DCHECK (because after calling this function they are
505 // expected to fail).
506 poisoned_ = true;
507}
508
[email protected]8d2e39e2013-06-24 05:55:08509// TODO(shess): To the extent possible, figure out the optimal
510// ordering for these deletes which will prevent other connections
511// from seeing odd behavior. For instance, it may be necessary to
512// manually lock the main database file in a SQLite-compatible fashion
513// (to prevent other processes from opening it), then delete the
514// journal files, then delete the main database file. Another option
515// might be to lock the main database file and poison the header with
516// junk to prevent other processes from opening it successfully (like
517// Gears "SQLite poison 3" trick).
518//
519// static
520bool Connection::Delete(const base::FilePath& path) {
521 base::ThreadRestrictions::AssertIOAllowed();
522
523 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
524 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
525
[email protected]dd3aa792013-07-16 19:10:23526 base::DeleteFile(journal_path, false);
527 base::DeleteFile(wal_path, false);
528 base::DeleteFile(path, false);
[email protected]8d2e39e2013-06-24 05:55:08529
[email protected]7567484142013-07-11 17:36:07530 return !base::PathExists(journal_path) &&
531 !base::PathExists(wal_path) &&
532 !base::PathExists(path);
[email protected]8d2e39e2013-06-24 05:55:08533}
534
[email protected]e5ffd0e42009-09-11 21:30:56535bool Connection::BeginTransaction() {
536 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33537 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56538
539 // When we're going to rollback, fail on this begin and don't actually
540 // mark us as entering the nested transaction.
541 return false;
542 }
543
544 bool success = true;
545 if (!transaction_nesting_) {
546 needs_rollback_ = false;
547
548 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:59549 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56550 return false;
551 }
552 transaction_nesting_++;
553 return success;
554}
555
556void Connection::RollbackTransaction() {
557 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38558 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56559 return;
560 }
561
562 transaction_nesting_--;
563
564 if (transaction_nesting_ > 0) {
565 // Mark the outermost transaction as needing rollback.
566 needs_rollback_ = true;
567 return;
568 }
569
570 DoRollback();
571}
572
573bool Connection::CommitTransaction() {
574 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38575 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56576 return false;
577 }
578 transaction_nesting_--;
579
580 if (transaction_nesting_ > 0) {
581 // Mark any nested transactions as failing after we've already got one.
582 return !needs_rollback_;
583 }
584
585 if (needs_rollback_) {
586 DoRollback();
587 return false;
588 }
589
590 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
[email protected]e5ffd0e42009-09-11 21:30:56591 return commit.Run();
592}
593
[email protected]8d409412013-07-19 18:25:30594void Connection::RollbackAllTransactions() {
595 if (transaction_nesting_ > 0) {
596 transaction_nesting_ = 0;
597 DoRollback();
598 }
599}
600
601bool Connection::AttachDatabase(const base::FilePath& other_db_path,
602 const char* attachment_point) {
603 DCHECK(ValidAttachmentPoint(attachment_point));
604
605 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
606#if OS_WIN
607 s.BindString16(0, other_db_path.value());
608#else
609 s.BindString(0, other_db_path.value());
610#endif
611 s.BindString(1, attachment_point);
612 return s.Run();
613}
614
615bool Connection::DetachDatabase(const char* attachment_point) {
616 DCHECK(ValidAttachmentPoint(attachment_point));
617
618 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
619 s.BindString(0, attachment_point);
620 return s.Run();
621}
622
[email protected]eff1fa522011-12-12 23:50:59623int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50624 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38625 if (!db_) {
626 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
627 return SQLITE_ERROR;
628 }
[email protected]eff1fa522011-12-12 23:50:59629 return sqlite3_exec(db_, sql, NULL, NULL, NULL);
630}
631
632bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:38633 if (!db_) {
634 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
635 return false;
636 }
637
[email protected]eff1fa522011-12-12 23:50:59638 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:00639 if (error != SQLITE_OK)
640 error = OnSqliteError(error, NULL);
641
[email protected]28fe0ff2012-02-25 00:40:33642 // This needs to be a FATAL log because the error case of arriving here is
643 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:10644 // a change alters the schema but not all queries adjust. This can happen
645 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:59646 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:33647 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:59648 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:56649}
650
[email protected]5b96f3772010-09-28 16:30:57651bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:38652 if (!db_) {
653 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:57654 return false;
[email protected]41a97c812013-02-07 02:35:38655 }
[email protected]5b96f3772010-09-28 16:30:57656
657 ScopedBusyTimeout busy_timeout(db_);
658 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:59659 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:57660}
661
[email protected]e5ffd0e42009-09-11 21:30:56662bool Connection::HasCachedStatement(const StatementID& id) const {
663 return statement_cache_.find(id) != statement_cache_.end();
664}
665
666scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
667 const StatementID& id,
668 const char* sql) {
669 CachedStatementMap::iterator i = statement_cache_.find(id);
670 if (i != statement_cache_.end()) {
671 // Statement is in the cache. It should still be active (we're the only
672 // one invalidating cached statements, and we'll remove it from the cache
673 // if we do that. Make sure we reset it before giving out the cached one in
674 // case it still has some stuff bound.
675 DCHECK(i->second->is_valid());
676 sqlite3_reset(i->second->stmt());
677 return i->second;
678 }
679
680 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
681 if (statement->is_valid())
682 statement_cache_[id] = statement; // Only cache valid statements.
683 return statement;
684}
685
686scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
687 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50688 AssertIOAllowed();
689
[email protected]41a97c812013-02-07 02:35:38690 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:56691 if (!db_)
[email protected]41a97c812013-02-07 02:35:38692 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:56693
694 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:00695 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
696 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:59697 // This is evidence of a syntax error in the incoming SQL.
698 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:00699
700 // It could also be database corruption.
701 OnSqliteError(rc, NULL);
[email protected]41a97c812013-02-07 02:35:38702 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:56703 }
[email protected]41a97c812013-02-07 02:35:38704 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:56705}
706
[email protected]2eec0a22012-07-24 01:59:58707scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
708 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:38709 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:58710 if (!db_)
[email protected]41a97c812013-02-07 02:35:38711 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:58712
713 sqlite3_stmt* stmt = NULL;
714 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
715 if (rc != SQLITE_OK) {
716 // This is evidence of a syntax error in the incoming SQL.
717 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:38718 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:58719 }
[email protected]41a97c812013-02-07 02:35:38720 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:58721}
722
[email protected]eff1fa522011-12-12 23:50:59723bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50724 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38725 if (!db_) {
726 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
727 return false;
728 }
729
[email protected]eff1fa522011-12-12 23:50:59730 sqlite3_stmt* stmt = NULL;
731 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
732 return false;
733
734 sqlite3_finalize(stmt);
735 return true;
736}
737
[email protected]1ed78a32009-09-15 20:24:17738bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:53739 return DoesTableOrIndexExist(table_name, "table");
740}
741
742bool Connection::DoesIndexExist(const char* index_name) const {
743 return DoesTableOrIndexExist(index_name, "index");
744}
745
746bool Connection::DoesTableOrIndexExist(
747 const char* name, const char* type) const {
[email protected]2eec0a22012-07-24 01:59:58748 const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?";
749 Statement statement(GetUntrackedStatement(kSql));
[email protected]e2cadec82011-12-13 02:00:53750 statement.BindString(0, type);
751 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:33752
[email protected]e5ffd0e42009-09-11 21:30:56753 return statement.Step(); // Table exists if any row was returned.
754}
755
756bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:17757 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:56758 std::string sql("PRAGMA TABLE_INFO(");
759 sql.append(table_name);
760 sql.append(")");
761
[email protected]2eec0a22012-07-24 01:59:58762 Statement statement(GetUntrackedStatement(sql.c_str()));
[email protected]e5ffd0e42009-09-11 21:30:56763 while (statement.Step()) {
764 if (!statement.ColumnString(1).compare(column_name))
765 return true;
766 }
767 return false;
768}
769
770int64 Connection::GetLastInsertRowId() const {
771 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38772 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:56773 return 0;
774 }
775 return sqlite3_last_insert_rowid(db_);
776}
777
[email protected]1ed78a32009-09-15 20:24:17778int Connection::GetLastChangeCount() const {
779 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38780 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:17781 return 0;
782 }
783 return sqlite3_changes(db_);
784}
785
[email protected]e5ffd0e42009-09-11 21:30:56786int Connection::GetErrorCode() const {
787 if (!db_)
788 return SQLITE_ERROR;
789 return sqlite3_errcode(db_);
790}
791
[email protected]767718e52010-09-21 23:18:49792int Connection::GetLastErrno() const {
793 if (!db_)
794 return -1;
795
796 int err = 0;
797 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
798 return -2;
799
800 return err;
801}
802
[email protected]e5ffd0e42009-09-11 21:30:56803const char* Connection::GetErrorMessage() const {
804 if (!db_)
805 return "sql::Connection has no connection.";
806 return sqlite3_errmsg(db_);
807}
808
[email protected]fed734a2013-07-17 04:45:13809bool Connection::OpenInternal(const std::string& file_name,
810 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:50811 AssertIOAllowed();
812
[email protected]9cfbc922009-11-17 20:13:17813 if (db_) {
[email protected]eff1fa522011-12-12 23:50:59814 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:17815 return false;
816 }
817
[email protected]a7ec1292013-07-22 22:02:18818 // Make sure sqlite3_initialize() is called before anything else.
819 InitializeSqlite();
820
[email protected]41a97c812013-02-07 02:35:38821 // If |poisoned_| is set, it means an error handler called
822 // RazeAndClose(). Until regular Close() is called, the caller
823 // should be treating the database as open, but is_open() currently
824 // only considers the sqlite3 handle's state.
825 // TODO(shess): Revise is_open() to consider poisoned_, and review
826 // to see if any non-testing code even depends on it.
827 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:16828 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:38829
[email protected]765b44502009-10-02 05:01:42830 int err = sqlite3_open(file_name.c_str(), &db_);
831 if (err != SQLITE_OK) {
[email protected]bd2ccdb4a2012-12-07 22:14:50832 // Histogram failures specific to initial open for debugging
833 // purposes.
834 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err & 0xff, 50);
835
[email protected]765b44502009-10-02 05:01:42836 OnSqliteError(err, NULL);
[email protected]fed734a2013-07-17 04:45:13837 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:29838 Close();
[email protected]fed734a2013-07-17 04:45:13839
840 if (was_poisoned && retry_flag == RETRY_ON_POISON)
841 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:42842 return false;
843 }
844
[email protected]81a2a602013-07-17 19:10:36845 // TODO(shess): OS_WIN support?
846#if defined(OS_POSIX)
847 if (restrict_to_user_) {
848 DCHECK_NE(file_name, std::string(":memory"));
849 base::FilePath file_path(file_name);
850 int mode = 0;
851 // TODO(shess): Arguably, failure to retrieve and change
852 // permissions should be fatal if the file exists.
853 if (file_util::GetPosixFilePermissions(file_path, &mode)) {
854 mode &= file_util::FILE_PERMISSION_USER_MASK;
855 file_util::SetPosixFilePermissions(file_path, mode);
856
857 // SQLite sets the permissions on these files from the main
858 // database on create. Set them here in case they already exist
859 // at this point. Failure to set these permissions should not
860 // be fatal unless the file doesn't exist.
861 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
862 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
863 file_util::SetPosixFilePermissions(journal_path, mode);
864 file_util::SetPosixFilePermissions(wal_path, mode);
865 }
866 }
867#endif // defined(OS_POSIX)
868
[email protected]affa2da2013-06-06 22:20:34869 // SQLite uses a lookaside buffer to improve performance of small mallocs.
870 // Chromium already depends on small mallocs being efficient, so we disable
871 // this to avoid the extra memory overhead.
872 // This must be called immediatly after opening the database before any SQL
873 // statements are run.
874 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
875
[email protected]bd2ccdb4a2012-12-07 22:14:50876 // sqlite3_open() does not actually read the database file (unless a
877 // hot journal is found). Successfully executing this pragma on an
878 // existing database requires a valid header on page 1.
879 // TODO(shess): For now, just probing to see what the lay of the
880 // land is. If it's mostly SQLITE_NOTADB, then the database should
881 // be razed.
882 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
883 if (err != SQLITE_OK)
884 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err & 0xff, 50);
885
[email protected]658f8332010-09-18 04:40:43886 // Enable extended result codes to provide more color on I/O errors.
887 // Not having extended result codes is not a fatal problem, as
888 // Chromium code does not attempt to handle I/O errors anyhow. The
889 // current implementation always returns SQLITE_OK, the DCHECK is to
890 // quickly notify someone if SQLite changes.
891 err = sqlite3_extended_result_codes(db_, 1);
892 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
893
[email protected]2e1cee762013-07-09 14:40:00894#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
895 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
896 // REGEXP support. Add it in dynamically.
897 err = sqlite3IcuInit(db_);
898 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
899#endif // OS_IOS && USE_SYSTEM_SQLITE
900
[email protected]5b96f3772010-09-28 16:30:57901 // If indicated, lock up the database before doing anything else, so
902 // that the following code doesn't have to deal with locking.
903 // TODO(shess): This code is brittle. Find the cases where code
904 // doesn't request |exclusive_locking_| and audit that it does the
905 // right thing with SQLITE_BUSY, and that it doesn't make
906 // assumptions about who might change things in the database.
907 // http://crbug.com/56559
908 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:10909 // TODO(shess): This should probably be a failure. Code which
910 // requests exclusive locking but doesn't get it is almost certain
911 // to be ill-tested.
912 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:57913 }
914
[email protected]4e179ba2012-03-17 16:06:47915 // http://www.sqlite.org/pragma.html#pragma_journal_mode
916 // DELETE (default) - delete -journal file to commit.
917 // TRUNCATE - truncate -journal file to commit.
918 // PERSIST - zero out header of -journal file to commit.
919 // journal_size_limit provides size to trim to in PERSIST.
920 // TODO(shess): Figure out if PERSIST and journal_size_limit really
921 // matter. In theory, it keeps pages pre-allocated, so if
922 // transactions usually fit, it should be faster.
923 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
924 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
925
[email protected]c68ce172011-11-24 22:30:27926 const base::TimeDelta kBusyTimeout =
927 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
928
[email protected]765b44502009-10-02 05:01:42929 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57930 // Enforce SQLite restrictions on |page_size_|.
931 DCHECK(!(page_size_ & (page_size_ - 1)))
932 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:24933 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:57934 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04935 const std::string sql =
936 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:10937 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:42938 }
939
940 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:04941 const std::string sql =
942 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:10943 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:42944 }
945
[email protected]6e0b1442011-08-09 23:23:58946 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:13947 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:58948 Close();
[email protected]fed734a2013-07-17 04:45:13949 if (was_poisoned && retry_flag == RETRY_ON_POISON)
950 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:58951 return false;
952 }
953
[email protected]765b44502009-10-02 05:01:42954 return true;
955}
956
[email protected]e5ffd0e42009-09-11 21:30:56957void Connection::DoRollback() {
958 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
[email protected]eff1fa522011-12-12 23:50:59959 rollback.Run();
[email protected]44ad7d902012-03-23 00:09:05960 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:56961}
962
963void Connection::StatementRefCreated(StatementRef* ref) {
964 DCHECK(open_statements_.find(ref) == open_statements_.end());
965 open_statements_.insert(ref);
966}
967
968void Connection::StatementRefDeleted(StatementRef* ref) {
969 StatementRefSet::iterator i = open_statements_.find(ref);
970 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:59971 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:56972 else
973 open_statements_.erase(i);
974}
975
[email protected]210ce0af2013-05-15 09:10:39976void Connection::AddTaggedHistogram(const std::string& name,
977 size_t sample) const {
978 if (histogram_tag_.empty())
979 return;
980
981 // TODO(shess): The histogram macros create a bit of static storage
982 // for caching the histogram object. This code shouldn't execute
983 // often enough for such caching to be crucial. If it becomes an
984 // issue, the object could be cached alongside histogram_prefix_.
985 std::string full_histogram_name = name + "." + histogram_tag_;
986 base::HistogramBase* histogram =
987 base::SparseHistogram::FactoryGet(
988 full_histogram_name,
989 base::HistogramBase::kUmaTargetedHistogramFlag);
990 if (histogram)
991 histogram->Add(sample);
992}
993
[email protected]faa604e2009-09-25 22:38:59994int Connection::OnSqliteError(int err, sql::Statement *stmt) {
[email protected]210ce0af2013-05-15 09:10:39995 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
996 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:14997
998 // Always log the error.
999 LOG(ERROR) << "sqlite error " << err
1000 << ", errno " << GetLastErrno()
1001 << ": " << GetErrorMessage();
1002
[email protected]c3881b372013-05-17 08:39:461003 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:561004 // Fire from a copy of the callback in case of reentry into
1005 // re/set_error_callback().
1006 // TODO(shess): <http://crbug.com/254584>
1007 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:461008 return err;
1009 }
1010
[email protected]faa604e2009-09-25 22:38:591011 // The default handling is to assert on debug and to ignore on release.
[email protected]4350e322013-06-18 22:18:101012 if (!ShouldIgnore(err))
1013 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:591014 return err;
1015}
1016
[email protected]80abf152013-05-22 12:42:421017// TODO(shess): Allow specifying integrity_check versus quick_check.
1018// TODO(shess): Allow specifying maximum results (default 100 lines).
1019bool Connection::IntegrityCheck(std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421020 messages->clear();
1021
[email protected]4658e2a02013-06-06 23:05:001022 // This has the side effect of setting SQLITE_RecoveryMode, which
1023 // allows SQLite to process through certain cases of corruption.
1024 // Failing to set this pragma probably means that the database is
1025 // beyond recovery.
1026 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1027 if (!Execute(kWritableSchema))
1028 return false;
1029
1030 bool ret = false;
1031 {
1032 const char kSql[] = "PRAGMA integrity_check";
1033 sql::Statement stmt(GetUniqueStatement(kSql));
1034
1035 // The pragma appears to return all results (up to 100 by default)
1036 // as a single string. This doesn't appear to be an API contract,
1037 // it could return separate lines, so loop _and_ split.
1038 while (stmt.Step()) {
1039 std::string result(stmt.ColumnString(0));
1040 base::SplitString(result, '\n', messages);
1041 }
1042 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421043 }
[email protected]4658e2a02013-06-06 23:05:001044
1045 // Best effort to put things back as they were before.
1046 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1047 ignore_result(Execute(kNoWritableSchema));
1048
1049 return ret;
[email protected]80abf152013-05-22 12:42:421050}
1051
[email protected]e5ffd0e42009-09-11 21:30:561052} // namespace sql