blob: 4550b0e5569304a75e77ef8a58298304fa7b2c1d [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]e5ffd0e42009-09-11 21:30:5611#include "base/logging.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5012#include "base/metrics/histogram.h"
[email protected]210ce0af2013-05-15 09:10:3913#include "base/metrics/sparse_histogram.h"
[email protected]80abf152013-05-22 12:42:4214#include "base/strings/string_split.h"
[email protected]a4bbc1f92013-06-11 07:28:1915#include "base/strings/string_util.h"
16#include "base/strings/stringprintf.h"
[email protected]906265872013-06-07 22:40:4517#include "base/strings/utf_string_conversions.h"
[email protected]f0a54b22011-07-19 18:40:2118#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0319#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5620
[email protected]2e1cee762013-07-09 14:40:0021#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
22#include "third_party/sqlite/src/ext/icu/sqliteicu.h"
23#endif
24
[email protected]5b96f3772010-09-28 16:30:5725namespace {
26
27// Spin for up to a second waiting for the lock to clear when setting
28// up the database.
29// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2730const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5731
32class ScopedBusyTimeout {
33 public:
34 explicit ScopedBusyTimeout(sqlite3* db)
35 : db_(db) {
36 }
37 ~ScopedBusyTimeout() {
38 sqlite3_busy_timeout(db_, 0);
39 }
40
41 int SetTimeout(base::TimeDelta timeout) {
42 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
43 return sqlite3_busy_timeout(db_,
44 static_cast<int>(timeout.InMilliseconds()));
45 }
46
47 private:
48 sqlite3* db_;
49};
50
[email protected]6d42f152012-11-10 00:38:2451// Helper to "safely" enable writable_schema. No error checking
52// because it is reasonable to just forge ahead in case of an error.
53// If turning it on fails, then most likely nothing will work, whereas
54// if turning it off fails, it only matters if some code attempts to
55// continue working with the database and tries to modify the
56// sqlite_master table (none of our code does this).
57class ScopedWritableSchema {
58 public:
59 explicit ScopedWritableSchema(sqlite3* db)
60 : db_(db) {
61 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
62 }
63 ~ScopedWritableSchema() {
64 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
65 }
66
67 private:
68 sqlite3* db_;
69};
70
[email protected]7bae5742013-07-10 20:46:1671// Helper to wrap the sqlite3_backup_*() step of Raze(). Return
72// SQLite error code from running the backup step.
73int BackupDatabase(sqlite3* src, sqlite3* dst, const char* db_name) {
74 DCHECK_NE(src, dst);
75 sqlite3_backup* backup = sqlite3_backup_init(dst, db_name, src, db_name);
76 if (!backup) {
77 // Since this call only sets things up, this indicates a gross
78 // error in SQLite.
79 DLOG(FATAL) << "Unable to start sqlite3_backup(): " << sqlite3_errmsg(dst);
80 return sqlite3_errcode(dst);
81 }
82
83 // -1 backs up the entire database.
84 int rc = sqlite3_backup_step(backup, -1);
85 int pages = sqlite3_backup_pagecount(backup);
86 sqlite3_backup_finish(backup);
87
88 // If successful, exactly one page should have been backed up. If
89 // this breaks, check this function to make sure assumptions aren't
90 // being broken.
91 if (rc == SQLITE_DONE)
92 DCHECK_EQ(pages, 1);
93
94 return rc;
95}
96
[email protected]8d409412013-07-19 18:25:3097// Be very strict on attachment point. SQLite can handle a much wider
98// character set with appropriate quoting, but Chromium code should
99// just use clean names to start with.
100bool ValidAttachmentPoint(const char* attachment_point) {
101 for (size_t i = 0; attachment_point[i]; ++i) {
102 if (!((attachment_point[i] >= '0' && attachment_point[i] <= '9') ||
103 (attachment_point[i] >= 'a' && attachment_point[i] <= 'z') ||
104 (attachment_point[i] >= 'A' && attachment_point[i] <= 'Z') ||
105 attachment_point[i] == '_')) {
106 return false;
107 }
108 }
109 return true;
110}
111
[email protected]5b96f3772010-09-28 16:30:57112} // namespace
113
[email protected]e5ffd0e42009-09-11 21:30:56114namespace sql {
115
[email protected]4350e322013-06-18 22:18:10116// static
117Connection::ErrorIgnorerCallback* Connection::current_ignorer_cb_ = NULL;
118
119// static
120bool Connection::ShouldIgnore(int error) {
121 if (!current_ignorer_cb_)
122 return false;
123 return current_ignorer_cb_->Run(error);
124}
125
126// static
127void Connection::SetErrorIgnorer(Connection::ErrorIgnorerCallback* cb) {
128 CHECK(current_ignorer_cb_ == NULL);
129 current_ignorer_cb_ = cb;
130}
131
132// static
133void Connection::ResetErrorIgnorer() {
134 CHECK(current_ignorer_cb_);
135 current_ignorer_cb_ = NULL;
136}
137
[email protected]e5ffd0e42009-09-11 21:30:56138bool StatementID::operator<(const StatementID& other) const {
139 if (number_ != other.number_)
140 return number_ < other.number_;
141 return strcmp(str_, other.str_) < 0;
142}
143
[email protected]e5ffd0e42009-09-11 21:30:56144Connection::StatementRef::StatementRef(Connection* connection,
[email protected]41a97c812013-02-07 02:35:38145 sqlite3_stmt* stmt,
146 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:56147 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:38148 stmt_(stmt),
149 was_valid_(was_valid) {
150 if (connection)
151 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:56152}
153
154Connection::StatementRef::~StatementRef() {
155 if (connection_)
156 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:38157 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:56158}
159
[email protected]41a97c812013-02-07 02:35:38160void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:56161 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50162 // Call to AssertIOAllowed() cannot go at the beginning of the function
163 // because Close() is called unconditionally from destructor to clean
164 // connection_. And if this is inactive statement this won't cause any
165 // disk access and destructor most probably will be called on thread
166 // not allowing disk access.
167 // TODO([email protected]): This should move to the beginning
168 // of the function. http://crbug.com/136655.
169 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56170 sqlite3_finalize(stmt_);
171 stmt_ = NULL;
172 }
173 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38174
175 // Forced close is expected to happen from a statement error
176 // handler. In that case maintain the sense of |was_valid_| which
177 // previously held for this ref.
178 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56179}
180
181Connection::Connection()
182 : db_(NULL),
183 page_size_(0),
184 cache_size_(0),
185 exclusive_locking_(false),
[email protected]81a2a602013-07-17 19:10:36186 restrict_to_user_(false),
[email protected]e5ffd0e42009-09-11 21:30:56187 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50188 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16189 in_memory_(false),
[email protected]526b4662013-06-14 04:09:12190 poisoned_(false) {
191}
[email protected]e5ffd0e42009-09-11 21:30:56192
193Connection::~Connection() {
194 Close();
195}
196
[email protected]a3ef4832013-02-02 05:12:33197bool Connection::Open(const base::FilePath& path) {
[email protected]348ac8f52013-05-21 03:27:02198 if (!histogram_tag_.empty()) {
199 int64 size_64 = 0;
200 if (file_util::GetFileSize(path, &size_64)) {
201 size_t sample = static_cast<size_t>(size_64 / 1024);
202 std::string full_histogram_name = "Sqlite.SizeKB." + histogram_tag_;
203 base::HistogramBase* histogram =
204 base::Histogram::FactoryGet(
205 full_histogram_name, 1, 1000000, 50,
206 base::HistogramBase::kUmaTargetedHistogramFlag);
207 if (histogram)
208 histogram->Add(sample);
209 }
210 }
211
[email protected]e5ffd0e42009-09-11 21:30:56212#if defined(OS_WIN)
[email protected]fed734a2013-07-17 04:45:13213 return OpenInternal(WideToUTF8(path.value()), RETRY_ON_POISON);
[email protected]e5ffd0e42009-09-11 21:30:56214#elif defined(OS_POSIX)
[email protected]fed734a2013-07-17 04:45:13215 return OpenInternal(path.value(), RETRY_ON_POISON);
[email protected]e5ffd0e42009-09-11 21:30:56216#endif
[email protected]765b44502009-10-02 05:01:42217}
[email protected]e5ffd0e42009-09-11 21:30:56218
[email protected]765b44502009-10-02 05:01:42219bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50220 in_memory_ = true;
[email protected]fed734a2013-07-17 04:45:13221 return OpenInternal(":memory:", NO_RETRY);
[email protected]e5ffd0e42009-09-11 21:30:56222}
223
[email protected]8d409412013-07-19 18:25:30224bool Connection::OpenTemporary() {
225 return OpenInternal("", NO_RETRY);
226}
227
[email protected]41a97c812013-02-07 02:35:38228void Connection::CloseInternal(bool forced) {
[email protected]4e179ba2012-03-17 16:06:47229 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
230 // will delete the -journal file. For ChromiumOS or other more
231 // embedded systems, this is probably not appropriate, whereas on
232 // desktop it might make some sense.
233
[email protected]4b350052012-02-24 20:40:48234 // sqlite3_close() needs all prepared statements to be finalized.
[email protected]4b350052012-02-24 20:40:48235
[email protected]41a97c812013-02-07 02:35:38236 // Release cached statements.
237 statement_cache_.clear();
238
239 // With cached statements released, in-use statements will remain.
240 // Closing the database while statements are in use is an API
241 // violation, except for forced close (which happens from within a
242 // statement's error handler).
243 DCHECK(forced || open_statements_.empty());
244
245 // Deactivate any outstanding statements so sqlite3_close() works.
246 for (StatementRefSet::iterator i = open_statements_.begin();
247 i != open_statements_.end(); ++i)
248 (*i)->Close(forced);
249 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48250
[email protected]e5ffd0e42009-09-11 21:30:56251 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50252 // Call to AssertIOAllowed() cannot go at the beginning of the function
253 // because Close() must be called from destructor to clean
254 // statement_cache_, it won't cause any disk access and it most probably
255 // will happen on thread not allowing disk access.
256 // TODO([email protected]): This should move to the beginning
257 // of the function. http://crbug.com/136655.
258 AssertIOAllowed();
[email protected]4b350052012-02-24 20:40:48259 // TODO(shess): Histogram for failure.
[email protected]e5ffd0e42009-09-11 21:30:56260 sqlite3_close(db_);
[email protected]e5ffd0e42009-09-11 21:30:56261 }
[email protected]fed734a2013-07-17 04:45:13262 db_ = NULL;
[email protected]e5ffd0e42009-09-11 21:30:56263}
264
[email protected]41a97c812013-02-07 02:35:38265void Connection::Close() {
266 // If the database was already closed by RazeAndClose(), then no
267 // need to close again. Clear the |poisoned_| bit so that incorrect
268 // API calls are caught.
269 if (poisoned_) {
270 poisoned_ = false;
271 return;
272 }
273
274 CloseInternal(false);
275}
276
[email protected]e5ffd0e42009-09-11 21:30:56277void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50278 AssertIOAllowed();
279
[email protected]e5ffd0e42009-09-11 21:30:56280 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38281 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56282 return;
283 }
284
285 // A statement must be open for the preload command to work. If the meta
286 // table doesn't exist, it probably means this is a new database and there
287 // is nothing to preload (so it's OK we do nothing).
288 if (!DoesTableExist("meta"))
289 return;
290 Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
[email protected]eff1fa522011-12-12 23:50:59291 if (!dummy.Step())
[email protected]e5ffd0e42009-09-11 21:30:56292 return;
293
[email protected]4176eee4b2011-01-26 14:33:32294#if !defined(USE_SYSTEM_SQLITE)
295 // This function is only defined in Chromium's version of sqlite.
296 // Do not call it when using system sqlite.
[email protected]67361b32011-04-12 20:13:06297 sqlite3_preload(db_);
[email protected]4176eee4b2011-01-26 14:33:32298#endif
[email protected]e5ffd0e42009-09-11 21:30:56299}
300
[email protected]be7995f12013-07-18 18:49:14301void Connection::TrimMemory(bool aggressively) {
302 if (!db_)
303 return;
304
305 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
306 int original_cache_size;
307 {
308 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
309 if (!sql_get_original.Step()) {
310 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
311 return;
312 }
313 original_cache_size = sql_get_original.ColumnInt(0);
314 }
315 int shrink_cache_size = aggressively ? 1 : (original_cache_size / 2);
316
317 // Force sqlite to try to reduce page cache usage.
318 const std::string sql_shrink =
319 base::StringPrintf("PRAGMA cache_size=%d", shrink_cache_size);
320 if (!Execute(sql_shrink.c_str()))
321 DLOG(WARNING) << "Could not shrink cache size: " << GetErrorMessage();
322
323 // Restore cache size.
324 const std::string sql_restore =
325 base::StringPrintf("PRAGMA cache_size=%d", original_cache_size);
326 if (!Execute(sql_restore.c_str()))
327 DLOG(WARNING) << "Could not restore cache size: " << GetErrorMessage();
328}
329
[email protected]8e0c01282012-04-06 19:36:49330// Create an in-memory database with the existing database's page
331// size, then backup that database over the existing database.
332bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50333 AssertIOAllowed();
334
[email protected]8e0c01282012-04-06 19:36:49335 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38336 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49337 return false;
338 }
339
340 if (transaction_nesting_ > 0) {
341 DLOG(FATAL) << "Cannot raze within a transaction";
342 return false;
343 }
344
345 sql::Connection null_db;
346 if (!null_db.OpenInMemory()) {
347 DLOG(FATAL) << "Unable to open in-memory database.";
348 return false;
349 }
350
[email protected]6d42f152012-11-10 00:38:24351 if (page_size_) {
352 // Enforce SQLite restrictions on |page_size_|.
353 DCHECK(!(page_size_ & (page_size_ - 1)))
354 << " page_size_ " << page_size_ << " is not a power of two.";
355 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
356 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04357 const std::string sql =
358 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:42359 if (!null_db.Execute(sql.c_str()))
360 return false;
361 }
362
[email protected]6d42f152012-11-10 00:38:24363#if defined(OS_ANDROID)
364 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
365 // in-memory databases do not respect this define.
366 // TODO(shess): Figure out a way to set this without using platform
367 // specific code. AFAICT from sqlite3.c, the only way to do it
368 // would be to create an actual filesystem database, which is
369 // unfortunate.
370 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
371 return false;
372#endif
[email protected]8e0c01282012-04-06 19:36:49373
374 // The page size doesn't take effect until a database has pages, and
375 // at this point the null database has none. Changing the schema
376 // version will create the first page. This will not affect the
377 // schema version in the resulting database, as SQLite's backup
378 // implementation propagates the schema version from the original
379 // connection to the new version of the database, incremented by one
380 // so that other readers see the schema change and act accordingly.
381 if (!null_db.Execute("PRAGMA schema_version = 1"))
382 return false;
383
[email protected]6d42f152012-11-10 00:38:24384 // SQLite tracks the expected number of database pages in the first
385 // page, and if it does not match the total retrieved from a
386 // filesystem call, treats the database as corrupt. This situation
387 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
388 // used to hint to SQLite to soldier on in that case, specifically
389 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
390 // sqlite3.c lockBtree().]
391 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
392 // page_size" can be used to query such a database.
393 ScopedWritableSchema writable_schema(db_);
394
[email protected]7bae5742013-07-10 20:46:16395 const char* kMain = "main";
396 int rc = BackupDatabase(null_db.db_, db_, kMain);
397 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase",rc);
[email protected]8e0c01282012-04-06 19:36:49398
399 // The destination database was locked.
400 if (rc == SQLITE_BUSY) {
401 return false;
402 }
403
[email protected]7bae5742013-07-10 20:46:16404 // SQLITE_NOTADB can happen if page 1 of db_ exists, but is not
405 // formatted correctly. SQLITE_IOERR_SHORT_READ can happen if db_
406 // isn't even big enough for one page. Either way, reach in and
407 // truncate it before trying again.
408 // TODO(shess): Maybe it would be worthwhile to just truncate from
409 // the get-go?
410 if (rc == SQLITE_NOTADB || rc == SQLITE_IOERR_SHORT_READ) {
411 sqlite3_file* file = NULL;
412 rc = sqlite3_file_control(db_, "main", SQLITE_FCNTL_FILE_POINTER, &file);
413 if (rc != SQLITE_OK) {
414 DLOG(FATAL) << "Failure getting file handle.";
415 return false;
416 } else if (!file) {
417 DLOG(FATAL) << "File handle is empty.";
418 return false;
419 }
420
421 rc = file->pMethods->xTruncate(file, 0);
422 if (rc != SQLITE_OK) {
423 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabaseTruncate",rc);
424 DLOG(FATAL) << "Failed to truncate file.";
425 return false;
426 }
427
428 rc = BackupDatabase(null_db.db_, db_, kMain);
429 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.RazeDatabase2",rc);
430
431 if (rc != SQLITE_DONE) {
432 DLOG(FATAL) << "Failed retrying Raze().";
433 }
434 }
435
[email protected]8e0c01282012-04-06 19:36:49436 // The entire database should have been backed up.
437 if (rc != SQLITE_DONE) {
[email protected]7bae5742013-07-10 20:46:16438 // TODO(shess): Figure out which other cases can happen.
[email protected]8e0c01282012-04-06 19:36:49439 DLOG(FATAL) << "Unable to copy entire null database.";
440 return false;
441 }
442
[email protected]8e0c01282012-04-06 19:36:49443 return true;
444}
445
446bool Connection::RazeWithTimout(base::TimeDelta timeout) {
447 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38448 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49449 return false;
450 }
451
452 ScopedBusyTimeout busy_timeout(db_);
453 busy_timeout.SetTimeout(timeout);
454 return Raze();
455}
456
[email protected]41a97c812013-02-07 02:35:38457bool Connection::RazeAndClose() {
458 if (!db_) {
459 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
460 return false;
461 }
462
463 // Raze() cannot run in a transaction.
[email protected]8d409412013-07-19 18:25:30464 RollbackAllTransactions();
[email protected]41a97c812013-02-07 02:35:38465
466 bool result = Raze();
467
468 CloseInternal(true);
469
470 // Mark the database so that future API calls fail appropriately,
471 // but don't DCHECK (because after calling this function they are
472 // expected to fail).
473 poisoned_ = true;
474
475 return result;
476}
477
[email protected]8d409412013-07-19 18:25:30478void Connection::Poison() {
479 if (!db_) {
480 DLOG_IF(FATAL, !poisoned_) << "Cannot poison null db";
481 return;
482 }
483
484 RollbackAllTransactions();
485 CloseInternal(true);
486
487 // Mark the database so that future API calls fail appropriately,
488 // but don't DCHECK (because after calling this function they are
489 // expected to fail).
490 poisoned_ = true;
491}
492
[email protected]8d2e39e2013-06-24 05:55:08493// TODO(shess): To the extent possible, figure out the optimal
494// ordering for these deletes which will prevent other connections
495// from seeing odd behavior. For instance, it may be necessary to
496// manually lock the main database file in a SQLite-compatible fashion
497// (to prevent other processes from opening it), then delete the
498// journal files, then delete the main database file. Another option
499// might be to lock the main database file and poison the header with
500// junk to prevent other processes from opening it successfully (like
501// Gears "SQLite poison 3" trick).
502//
503// static
504bool Connection::Delete(const base::FilePath& path) {
505 base::ThreadRestrictions::AssertIOAllowed();
506
507 base::FilePath journal_path(path.value() + FILE_PATH_LITERAL("-journal"));
508 base::FilePath wal_path(path.value() + FILE_PATH_LITERAL("-wal"));
509
[email protected]dd3aa792013-07-16 19:10:23510 base::DeleteFile(journal_path, false);
511 base::DeleteFile(wal_path, false);
512 base::DeleteFile(path, false);
[email protected]8d2e39e2013-06-24 05:55:08513
[email protected]7567484142013-07-11 17:36:07514 return !base::PathExists(journal_path) &&
515 !base::PathExists(wal_path) &&
516 !base::PathExists(path);
[email protected]8d2e39e2013-06-24 05:55:08517}
518
[email protected]e5ffd0e42009-09-11 21:30:56519bool Connection::BeginTransaction() {
520 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33521 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56522
523 // When we're going to rollback, fail on this begin and don't actually
524 // mark us as entering the nested transaction.
525 return false;
526 }
527
528 bool success = true;
529 if (!transaction_nesting_) {
530 needs_rollback_ = false;
531
532 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:59533 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56534 return false;
535 }
536 transaction_nesting_++;
537 return success;
538}
539
540void Connection::RollbackTransaction() {
541 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38542 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56543 return;
544 }
545
546 transaction_nesting_--;
547
548 if (transaction_nesting_ > 0) {
549 // Mark the outermost transaction as needing rollback.
550 needs_rollback_ = true;
551 return;
552 }
553
554 DoRollback();
555}
556
557bool Connection::CommitTransaction() {
558 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38559 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56560 return false;
561 }
562 transaction_nesting_--;
563
564 if (transaction_nesting_ > 0) {
565 // Mark any nested transactions as failing after we've already got one.
566 return !needs_rollback_;
567 }
568
569 if (needs_rollback_) {
570 DoRollback();
571 return false;
572 }
573
574 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
[email protected]e5ffd0e42009-09-11 21:30:56575 return commit.Run();
576}
577
[email protected]8d409412013-07-19 18:25:30578void Connection::RollbackAllTransactions() {
579 if (transaction_nesting_ > 0) {
580 transaction_nesting_ = 0;
581 DoRollback();
582 }
583}
584
585bool Connection::AttachDatabase(const base::FilePath& other_db_path,
586 const char* attachment_point) {
587 DCHECK(ValidAttachmentPoint(attachment_point));
588
589 Statement s(GetUniqueStatement("ATTACH DATABASE ? AS ?"));
590#if OS_WIN
591 s.BindString16(0, other_db_path.value());
592#else
593 s.BindString(0, other_db_path.value());
594#endif
595 s.BindString(1, attachment_point);
596 return s.Run();
597}
598
599bool Connection::DetachDatabase(const char* attachment_point) {
600 DCHECK(ValidAttachmentPoint(attachment_point));
601
602 Statement s(GetUniqueStatement("DETACH DATABASE ?"));
603 s.BindString(0, attachment_point);
604 return s.Run();
605}
606
[email protected]eff1fa522011-12-12 23:50:59607int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50608 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38609 if (!db_) {
610 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
611 return SQLITE_ERROR;
612 }
[email protected]eff1fa522011-12-12 23:50:59613 return sqlite3_exec(db_, sql, NULL, NULL, NULL);
614}
615
616bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:38617 if (!db_) {
618 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
619 return false;
620 }
621
[email protected]eff1fa522011-12-12 23:50:59622 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:00623 if (error != SQLITE_OK)
624 error = OnSqliteError(error, NULL);
625
[email protected]28fe0ff2012-02-25 00:40:33626 // This needs to be a FATAL log because the error case of arriving here is
627 // that there's a malformed SQL statement. This can arise in development if
[email protected]4350e322013-06-18 22:18:10628 // a change alters the schema but not all queries adjust. This can happen
629 // in production if the schema is corrupted.
[email protected]eff1fa522011-12-12 23:50:59630 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:33631 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:59632 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:56633}
634
[email protected]5b96f3772010-09-28 16:30:57635bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:38636 if (!db_) {
637 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:57638 return false;
[email protected]41a97c812013-02-07 02:35:38639 }
[email protected]5b96f3772010-09-28 16:30:57640
641 ScopedBusyTimeout busy_timeout(db_);
642 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:59643 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:57644}
645
[email protected]e5ffd0e42009-09-11 21:30:56646bool Connection::HasCachedStatement(const StatementID& id) const {
647 return statement_cache_.find(id) != statement_cache_.end();
648}
649
650scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
651 const StatementID& id,
652 const char* sql) {
653 CachedStatementMap::iterator i = statement_cache_.find(id);
654 if (i != statement_cache_.end()) {
655 // Statement is in the cache. It should still be active (we're the only
656 // one invalidating cached statements, and we'll remove it from the cache
657 // if we do that. Make sure we reset it before giving out the cached one in
658 // case it still has some stuff bound.
659 DCHECK(i->second->is_valid());
660 sqlite3_reset(i->second->stmt());
661 return i->second;
662 }
663
664 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
665 if (statement->is_valid())
666 statement_cache_[id] = statement; // Only cache valid statements.
667 return statement;
668}
669
670scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
671 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50672 AssertIOAllowed();
673
[email protected]41a97c812013-02-07 02:35:38674 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:56675 if (!db_)
[email protected]41a97c812013-02-07 02:35:38676 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:56677
678 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:00679 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
680 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:59681 // This is evidence of a syntax error in the incoming SQL.
682 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:00683
684 // It could also be database corruption.
685 OnSqliteError(rc, NULL);
[email protected]41a97c812013-02-07 02:35:38686 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:56687 }
[email protected]41a97c812013-02-07 02:35:38688 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:56689}
690
[email protected]2eec0a22012-07-24 01:59:58691scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
692 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:38693 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:58694 if (!db_)
[email protected]41a97c812013-02-07 02:35:38695 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:58696
697 sqlite3_stmt* stmt = NULL;
698 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
699 if (rc != SQLITE_OK) {
700 // This is evidence of a syntax error in the incoming SQL.
701 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:38702 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:58703 }
[email protected]41a97c812013-02-07 02:35:38704 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:58705}
706
[email protected]eff1fa522011-12-12 23:50:59707bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50708 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38709 if (!db_) {
710 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
711 return false;
712 }
713
[email protected]eff1fa522011-12-12 23:50:59714 sqlite3_stmt* stmt = NULL;
715 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
716 return false;
717
718 sqlite3_finalize(stmt);
719 return true;
720}
721
[email protected]1ed78a32009-09-15 20:24:17722bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:53723 return DoesTableOrIndexExist(table_name, "table");
724}
725
726bool Connection::DoesIndexExist(const char* index_name) const {
727 return DoesTableOrIndexExist(index_name, "index");
728}
729
730bool Connection::DoesTableOrIndexExist(
731 const char* name, const char* type) const {
[email protected]2eec0a22012-07-24 01:59:58732 const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?";
733 Statement statement(GetUntrackedStatement(kSql));
[email protected]e2cadec82011-12-13 02:00:53734 statement.BindString(0, type);
735 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:33736
[email protected]e5ffd0e42009-09-11 21:30:56737 return statement.Step(); // Table exists if any row was returned.
738}
739
740bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:17741 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:56742 std::string sql("PRAGMA TABLE_INFO(");
743 sql.append(table_name);
744 sql.append(")");
745
[email protected]2eec0a22012-07-24 01:59:58746 Statement statement(GetUntrackedStatement(sql.c_str()));
[email protected]e5ffd0e42009-09-11 21:30:56747 while (statement.Step()) {
748 if (!statement.ColumnString(1).compare(column_name))
749 return true;
750 }
751 return false;
752}
753
754int64 Connection::GetLastInsertRowId() const {
755 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38756 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:56757 return 0;
758 }
759 return sqlite3_last_insert_rowid(db_);
760}
761
[email protected]1ed78a32009-09-15 20:24:17762int Connection::GetLastChangeCount() const {
763 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38764 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:17765 return 0;
766 }
767 return sqlite3_changes(db_);
768}
769
[email protected]e5ffd0e42009-09-11 21:30:56770int Connection::GetErrorCode() const {
771 if (!db_)
772 return SQLITE_ERROR;
773 return sqlite3_errcode(db_);
774}
775
[email protected]767718e52010-09-21 23:18:49776int Connection::GetLastErrno() const {
777 if (!db_)
778 return -1;
779
780 int err = 0;
781 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
782 return -2;
783
784 return err;
785}
786
[email protected]e5ffd0e42009-09-11 21:30:56787const char* Connection::GetErrorMessage() const {
788 if (!db_)
789 return "sql::Connection has no connection.";
790 return sqlite3_errmsg(db_);
791}
792
[email protected]fed734a2013-07-17 04:45:13793bool Connection::OpenInternal(const std::string& file_name,
794 Connection::Retry retry_flag) {
[email protected]35f7e5392012-07-27 19:54:50795 AssertIOAllowed();
796
[email protected]9cfbc922009-11-17 20:13:17797 if (db_) {
[email protected]eff1fa522011-12-12 23:50:59798 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:17799 return false;
800 }
801
[email protected]41a97c812013-02-07 02:35:38802 // If |poisoned_| is set, it means an error handler called
803 // RazeAndClose(). Until regular Close() is called, the caller
804 // should be treating the database as open, but is_open() currently
805 // only considers the sqlite3 handle's state.
806 // TODO(shess): Revise is_open() to consider poisoned_, and review
807 // to see if any non-testing code even depends on it.
808 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
[email protected]7bae5742013-07-10 20:46:16809 poisoned_ = false;
[email protected]41a97c812013-02-07 02:35:38810
[email protected]765b44502009-10-02 05:01:42811 int err = sqlite3_open(file_name.c_str(), &db_);
812 if (err != SQLITE_OK) {
[email protected]bd2ccdb4a2012-12-07 22:14:50813 // Histogram failures specific to initial open for debugging
814 // purposes.
815 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err & 0xff, 50);
816
[email protected]765b44502009-10-02 05:01:42817 OnSqliteError(err, NULL);
[email protected]fed734a2013-07-17 04:45:13818 bool was_poisoned = poisoned_;
[email protected]64021042012-02-10 20:02:29819 Close();
[email protected]fed734a2013-07-17 04:45:13820
821 if (was_poisoned && retry_flag == RETRY_ON_POISON)
822 return OpenInternal(file_name, NO_RETRY);
[email protected]765b44502009-10-02 05:01:42823 return false;
824 }
825
[email protected]81a2a602013-07-17 19:10:36826 // TODO(shess): OS_WIN support?
827#if defined(OS_POSIX)
828 if (restrict_to_user_) {
829 DCHECK_NE(file_name, std::string(":memory"));
830 base::FilePath file_path(file_name);
831 int mode = 0;
832 // TODO(shess): Arguably, failure to retrieve and change
833 // permissions should be fatal if the file exists.
834 if (file_util::GetPosixFilePermissions(file_path, &mode)) {
835 mode &= file_util::FILE_PERMISSION_USER_MASK;
836 file_util::SetPosixFilePermissions(file_path, mode);
837
838 // SQLite sets the permissions on these files from the main
839 // database on create. Set them here in case they already exist
840 // at this point. Failure to set these permissions should not
841 // be fatal unless the file doesn't exist.
842 base::FilePath journal_path(file_name + FILE_PATH_LITERAL("-journal"));
843 base::FilePath wal_path(file_name + FILE_PATH_LITERAL("-wal"));
844 file_util::SetPosixFilePermissions(journal_path, mode);
845 file_util::SetPosixFilePermissions(wal_path, mode);
846 }
847 }
848#endif // defined(OS_POSIX)
849
[email protected]affa2da2013-06-06 22:20:34850 // SQLite uses a lookaside buffer to improve performance of small mallocs.
851 // Chromium already depends on small mallocs being efficient, so we disable
852 // this to avoid the extra memory overhead.
853 // This must be called immediatly after opening the database before any SQL
854 // statements are run.
855 sqlite3_db_config(db_, SQLITE_DBCONFIG_LOOKASIDE, NULL, 0, 0);
856
[email protected]bd2ccdb4a2012-12-07 22:14:50857 // sqlite3_open() does not actually read the database file (unless a
858 // hot journal is found). Successfully executing this pragma on an
859 // existing database requires a valid header on page 1.
860 // TODO(shess): For now, just probing to see what the lay of the
861 // land is. If it's mostly SQLITE_NOTADB, then the database should
862 // be razed.
863 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
864 if (err != SQLITE_OK)
865 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err & 0xff, 50);
866
[email protected]658f8332010-09-18 04:40:43867 // Enable extended result codes to provide more color on I/O errors.
868 // Not having extended result codes is not a fatal problem, as
869 // Chromium code does not attempt to handle I/O errors anyhow. The
870 // current implementation always returns SQLITE_OK, the DCHECK is to
871 // quickly notify someone if SQLite changes.
872 err = sqlite3_extended_result_codes(db_, 1);
873 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
874
[email protected]2e1cee762013-07-09 14:40:00875#if defined(OS_IOS) && defined(USE_SYSTEM_SQLITE)
876 // The version of SQLite shipped with iOS doesn't enable ICU, which includes
877 // REGEXP support. Add it in dynamically.
878 err = sqlite3IcuInit(db_);
879 DCHECK_EQ(err, SQLITE_OK) << "Could not enable ICU support";
880#endif // OS_IOS && USE_SYSTEM_SQLITE
881
[email protected]5b96f3772010-09-28 16:30:57882 // If indicated, lock up the database before doing anything else, so
883 // that the following code doesn't have to deal with locking.
884 // TODO(shess): This code is brittle. Find the cases where code
885 // doesn't request |exclusive_locking_| and audit that it does the
886 // right thing with SQLITE_BUSY, and that it doesn't make
887 // assumptions about who might change things in the database.
888 // http://crbug.com/56559
889 if (exclusive_locking_) {
[email protected]4350e322013-06-18 22:18:10890 // TODO(shess): This should probably be a failure. Code which
891 // requests exclusive locking but doesn't get it is almost certain
892 // to be ill-tested.
893 ignore_result(Execute("PRAGMA locking_mode=EXCLUSIVE"));
[email protected]5b96f3772010-09-28 16:30:57894 }
895
[email protected]4e179ba2012-03-17 16:06:47896 // http://www.sqlite.org/pragma.html#pragma_journal_mode
897 // DELETE (default) - delete -journal file to commit.
898 // TRUNCATE - truncate -journal file to commit.
899 // PERSIST - zero out header of -journal file to commit.
900 // journal_size_limit provides size to trim to in PERSIST.
901 // TODO(shess): Figure out if PERSIST and journal_size_limit really
902 // matter. In theory, it keeps pages pre-allocated, so if
903 // transactions usually fit, it should be faster.
904 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
905 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
906
[email protected]c68ce172011-11-24 22:30:27907 const base::TimeDelta kBusyTimeout =
908 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
909
[email protected]765b44502009-10-02 05:01:42910 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57911 // Enforce SQLite restrictions on |page_size_|.
912 DCHECK(!(page_size_ & (page_size_ - 1)))
913 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:24914 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:57915 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04916 const std::string sql =
917 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]4350e322013-06-18 22:18:10918 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:42919 }
920
921 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:04922 const std::string sql =
923 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]4350e322013-06-18 22:18:10924 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
[email protected]765b44502009-10-02 05:01:42925 }
926
[email protected]6e0b1442011-08-09 23:23:58927 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]fed734a2013-07-17 04:45:13928 bool was_poisoned = poisoned_;
[email protected]6e0b1442011-08-09 23:23:58929 Close();
[email protected]fed734a2013-07-17 04:45:13930 if (was_poisoned && retry_flag == RETRY_ON_POISON)
931 return OpenInternal(file_name, NO_RETRY);
[email protected]6e0b1442011-08-09 23:23:58932 return false;
933 }
934
[email protected]765b44502009-10-02 05:01:42935 return true;
936}
937
[email protected]e5ffd0e42009-09-11 21:30:56938void Connection::DoRollback() {
939 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
[email protected]eff1fa522011-12-12 23:50:59940 rollback.Run();
[email protected]44ad7d902012-03-23 00:09:05941 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:56942}
943
944void Connection::StatementRefCreated(StatementRef* ref) {
945 DCHECK(open_statements_.find(ref) == open_statements_.end());
946 open_statements_.insert(ref);
947}
948
949void Connection::StatementRefDeleted(StatementRef* ref) {
950 StatementRefSet::iterator i = open_statements_.find(ref);
951 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:59952 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:56953 else
954 open_statements_.erase(i);
955}
956
[email protected]210ce0af2013-05-15 09:10:39957void Connection::AddTaggedHistogram(const std::string& name,
958 size_t sample) const {
959 if (histogram_tag_.empty())
960 return;
961
962 // TODO(shess): The histogram macros create a bit of static storage
963 // for caching the histogram object. This code shouldn't execute
964 // often enough for such caching to be crucial. If it becomes an
965 // issue, the object could be cached alongside histogram_prefix_.
966 std::string full_histogram_name = name + "." + histogram_tag_;
967 base::HistogramBase* histogram =
968 base::SparseHistogram::FactoryGet(
969 full_histogram_name,
970 base::HistogramBase::kUmaTargetedHistogramFlag);
971 if (histogram)
972 histogram->Add(sample);
973}
974
[email protected]faa604e2009-09-25 22:38:59975int Connection::OnSqliteError(int err, sql::Statement *stmt) {
[email protected]210ce0af2013-05-15 09:10:39976 UMA_HISTOGRAM_SPARSE_SLOWLY("Sqlite.Error", err);
977 AddTaggedHistogram("Sqlite.Error", err);
[email protected]c088e3a32013-01-03 23:59:14978
979 // Always log the error.
980 LOG(ERROR) << "sqlite error " << err
981 << ", errno " << GetLastErrno()
982 << ": " << GetErrorMessage();
983
[email protected]c3881b372013-05-17 08:39:46984 if (!error_callback_.is_null()) {
[email protected]98cf3002013-07-12 01:38:56985 // Fire from a copy of the callback in case of reentry into
986 // re/set_error_callback().
987 // TODO(shess): <http://crbug.com/254584>
988 ErrorCallback(error_callback_).Run(err, stmt);
[email protected]c3881b372013-05-17 08:39:46989 return err;
990 }
991
[email protected]faa604e2009-09-25 22:38:59992 // The default handling is to assert on debug and to ignore on release.
[email protected]4350e322013-06-18 22:18:10993 if (!ShouldIgnore(err))
994 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:59995 return err;
996}
997
[email protected]80abf152013-05-22 12:42:42998// TODO(shess): Allow specifying integrity_check versus quick_check.
999// TODO(shess): Allow specifying maximum results (default 100 lines).
1000bool Connection::IntegrityCheck(std::vector<std::string>* messages) {
[email protected]80abf152013-05-22 12:42:421001 messages->clear();
1002
[email protected]4658e2a02013-06-06 23:05:001003 // This has the side effect of setting SQLITE_RecoveryMode, which
1004 // allows SQLite to process through certain cases of corruption.
1005 // Failing to set this pragma probably means that the database is
1006 // beyond recovery.
1007 const char kWritableSchema[] = "PRAGMA writable_schema = ON";
1008 if (!Execute(kWritableSchema))
1009 return false;
1010
1011 bool ret = false;
1012 {
1013 const char kSql[] = "PRAGMA integrity_check";
1014 sql::Statement stmt(GetUniqueStatement(kSql));
1015
1016 // The pragma appears to return all results (up to 100 by default)
1017 // as a single string. This doesn't appear to be an API contract,
1018 // it could return separate lines, so loop _and_ split.
1019 while (stmt.Step()) {
1020 std::string result(stmt.ColumnString(0));
1021 base::SplitString(result, '\n', messages);
1022 }
1023 ret = stmt.Succeeded();
[email protected]80abf152013-05-22 12:42:421024 }
[email protected]4658e2a02013-06-06 23:05:001025
1026 // Best effort to put things back as they were before.
1027 const char kNoWritableSchema[] = "PRAGMA writable_schema = OFF";
1028 ignore_result(Execute(kNoWritableSchema));
1029
1030 return ret;
[email protected]80abf152013-05-22 12:42:421031}
1032
[email protected]e5ffd0e42009-09-11 21:30:561033} // namespace sql