blob: aefac60fac7e3fa37b75611eebf3dba457e48204 [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]e5ffd0e42009-09-11 21:30:569#include "base/file_path.h"
10#include "base/logging.h"
[email protected]bd2ccdb4a2012-12-07 22:14:5011#include "base/metrics/histogram.h"
[email protected]e5ffd0e42009-09-11 21:30:5612#include "base/string_util.h"
[email protected]f0a54b22011-07-19 18:40:2113#include "base/stringprintf.h"
[email protected]d55194ca2010-03-11 18:25:4514#include "base/utf_string_conversions.h"
[email protected]f0a54b22011-07-19 18:40:2115#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0316#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5617
[email protected]5b96f3772010-09-28 16:30:5718namespace {
19
20// Spin for up to a second waiting for the lock to clear when setting
21// up the database.
22// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2723const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5724
25class ScopedBusyTimeout {
26 public:
27 explicit ScopedBusyTimeout(sqlite3* db)
28 : db_(db) {
29 }
30 ~ScopedBusyTimeout() {
31 sqlite3_busy_timeout(db_, 0);
32 }
33
34 int SetTimeout(base::TimeDelta timeout) {
35 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
36 return sqlite3_busy_timeout(db_,
37 static_cast<int>(timeout.InMilliseconds()));
38 }
39
40 private:
41 sqlite3* db_;
42};
43
[email protected]6d42f152012-11-10 00:38:2444// Helper to "safely" enable writable_schema. No error checking
45// because it is reasonable to just forge ahead in case of an error.
46// If turning it on fails, then most likely nothing will work, whereas
47// if turning it off fails, it only matters if some code attempts to
48// continue working with the database and tries to modify the
49// sqlite_master table (none of our code does this).
50class ScopedWritableSchema {
51 public:
52 explicit ScopedWritableSchema(sqlite3* db)
53 : db_(db) {
54 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
55 }
56 ~ScopedWritableSchema() {
57 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
58 }
59
60 private:
61 sqlite3* db_;
62};
63
[email protected]5b96f3772010-09-28 16:30:5764} // namespace
65
[email protected]e5ffd0e42009-09-11 21:30:5666namespace sql {
67
68bool StatementID::operator<(const StatementID& other) const {
69 if (number_ != other.number_)
70 return number_ < other.number_;
71 return strcmp(str_, other.str_) < 0;
72}
73
[email protected]d4799a32010-09-28 22:54:5874ErrorDelegate::~ErrorDelegate() {
75}
76
[email protected]e5ffd0e42009-09-11 21:30:5677Connection::StatementRef::StatementRef()
78 : connection_(NULL),
79 stmt_(NULL) {
80}
81
[email protected]2eec0a22012-07-24 01:59:5882Connection::StatementRef::StatementRef(sqlite3_stmt* stmt)
83 : connection_(NULL),
84 stmt_(stmt) {
85}
86
[email protected]e5ffd0e42009-09-11 21:30:5687Connection::StatementRef::StatementRef(Connection* connection,
88 sqlite3_stmt* stmt)
89 : connection_(connection),
90 stmt_(stmt) {
91 connection_->StatementRefCreated(this);
92}
93
94Connection::StatementRef::~StatementRef() {
95 if (connection_)
96 connection_->StatementRefDeleted(this);
97 Close();
98}
99
100void Connection::StatementRef::Close() {
101 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50102 // Call to AssertIOAllowed() cannot go at the beginning of the function
103 // because Close() is called unconditionally from destructor to clean
104 // connection_. And if this is inactive statement this won't cause any
105 // disk access and destructor most probably will be called on thread
106 // not allowing disk access.
107 // TODO([email protected]): This should move to the beginning
108 // of the function. http://crbug.com/136655.
109 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56110 sqlite3_finalize(stmt_);
111 stmt_ = NULL;
112 }
113 connection_ = NULL; // The connection may be getting deleted.
114}
115
116Connection::Connection()
117 : db_(NULL),
118 page_size_(0),
119 cache_size_(0),
120 exclusive_locking_(false),
121 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50122 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16123 in_memory_(false),
124 error_delegate_(NULL) {
[email protected]e5ffd0e42009-09-11 21:30:56125}
126
127Connection::~Connection() {
128 Close();
129}
130
[email protected]765b44502009-10-02 05:01:42131bool Connection::Open(const FilePath& path) {
[email protected]e5ffd0e42009-09-11 21:30:56132#if defined(OS_WIN)
[email protected]765b44502009-10-02 05:01:42133 return OpenInternal(WideToUTF8(path.value()));
[email protected]e5ffd0e42009-09-11 21:30:56134#elif defined(OS_POSIX)
[email protected]765b44502009-10-02 05:01:42135 return OpenInternal(path.value());
[email protected]e5ffd0e42009-09-11 21:30:56136#endif
[email protected]765b44502009-10-02 05:01:42137}
[email protected]e5ffd0e42009-09-11 21:30:56138
[email protected]765b44502009-10-02 05:01:42139bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50140 in_memory_ = true;
[email protected]765b44502009-10-02 05:01:42141 return OpenInternal(":memory:");
[email protected]e5ffd0e42009-09-11 21:30:56142}
143
144void Connection::Close() {
[email protected]4e179ba2012-03-17 16:06:47145 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
146 // will delete the -journal file. For ChromiumOS or other more
147 // embedded systems, this is probably not appropriate, whereas on
148 // desktop it might make some sense.
149
[email protected]4b350052012-02-24 20:40:48150 // sqlite3_close() needs all prepared statements to be finalized.
151 // Release all cached statements, then assert that the client has
152 // released all statements.
[email protected]e5ffd0e42009-09-11 21:30:56153 statement_cache_.clear();
154 DCHECK(open_statements_.empty());
[email protected]4b350052012-02-24 20:40:48155
156 // Additionally clear the prepared statements, because they contain
157 // weak references to this connection. This case has come up when
158 // error-handling code is hit in production.
159 ClearCache();
160
[email protected]e5ffd0e42009-09-11 21:30:56161 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50162 // Call to AssertIOAllowed() cannot go at the beginning of the function
163 // because Close() must be called from destructor to clean
164 // statement_cache_, it won't cause any disk access and it most probably
165 // will happen on thread not allowing disk access.
166 // TODO([email protected]): This should move to the beginning
167 // of the function. http://crbug.com/136655.
168 AssertIOAllowed();
[email protected]4b350052012-02-24 20:40:48169 // TODO(shess): Histogram for failure.
[email protected]e5ffd0e42009-09-11 21:30:56170 sqlite3_close(db_);
171 db_ = NULL;
172 }
173}
174
175void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50176 AssertIOAllowed();
177
[email protected]e5ffd0e42009-09-11 21:30:56178 if (!db_) {
[email protected]eff1fa522011-12-12 23:50:59179 DLOG(FATAL) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56180 return;
181 }
182
183 // A statement must be open for the preload command to work. If the meta
184 // table doesn't exist, it probably means this is a new database and there
185 // is nothing to preload (so it's OK we do nothing).
186 if (!DoesTableExist("meta"))
187 return;
188 Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
[email protected]eff1fa522011-12-12 23:50:59189 if (!dummy.Step())
[email protected]e5ffd0e42009-09-11 21:30:56190 return;
191
[email protected]4176eee4b2011-01-26 14:33:32192#if !defined(USE_SYSTEM_SQLITE)
193 // This function is only defined in Chromium's version of sqlite.
194 // Do not call it when using system sqlite.
[email protected]67361b32011-04-12 20:13:06195 sqlite3_preload(db_);
[email protected]4176eee4b2011-01-26 14:33:32196#endif
[email protected]e5ffd0e42009-09-11 21:30:56197}
198
[email protected]8e0c01282012-04-06 19:36:49199// Create an in-memory database with the existing database's page
200// size, then backup that database over the existing database.
201bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50202 AssertIOAllowed();
203
[email protected]8e0c01282012-04-06 19:36:49204 if (!db_) {
205 DLOG(FATAL) << "Cannot raze null db";
206 return false;
207 }
208
209 if (transaction_nesting_ > 0) {
210 DLOG(FATAL) << "Cannot raze within a transaction";
211 return false;
212 }
213
214 sql::Connection null_db;
215 if (!null_db.OpenInMemory()) {
216 DLOG(FATAL) << "Unable to open in-memory database.";
217 return false;
218 }
219
[email protected]6d42f152012-11-10 00:38:24220 if (page_size_) {
221 // Enforce SQLite restrictions on |page_size_|.
222 DCHECK(!(page_size_ & (page_size_ - 1)))
223 << " page_size_ " << page_size_ << " is not a power of two.";
224 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
225 DCHECK_LE(page_size_, kSqliteMaxPageSize);
226 const std::string sql = StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:42227 if (!null_db.Execute(sql.c_str()))
228 return false;
229 }
230
[email protected]6d42f152012-11-10 00:38:24231#if defined(OS_ANDROID)
232 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
233 // in-memory databases do not respect this define.
234 // TODO(shess): Figure out a way to set this without using platform
235 // specific code. AFAICT from sqlite3.c, the only way to do it
236 // would be to create an actual filesystem database, which is
237 // unfortunate.
238 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
239 return false;
240#endif
[email protected]8e0c01282012-04-06 19:36:49241
242 // The page size doesn't take effect until a database has pages, and
243 // at this point the null database has none. Changing the schema
244 // version will create the first page. This will not affect the
245 // schema version in the resulting database, as SQLite's backup
246 // implementation propagates the schema version from the original
247 // connection to the new version of the database, incremented by one
248 // so that other readers see the schema change and act accordingly.
249 if (!null_db.Execute("PRAGMA schema_version = 1"))
250 return false;
251
[email protected]6d42f152012-11-10 00:38:24252 // SQLite tracks the expected number of database pages in the first
253 // page, and if it does not match the total retrieved from a
254 // filesystem call, treats the database as corrupt. This situation
255 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
256 // used to hint to SQLite to soldier on in that case, specifically
257 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
258 // sqlite3.c lockBtree().]
259 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
260 // page_size" can be used to query such a database.
261 ScopedWritableSchema writable_schema(db_);
262
[email protected]8e0c01282012-04-06 19:36:49263 sqlite3_backup* backup = sqlite3_backup_init(db_, "main",
264 null_db.db_, "main");
265 if (!backup) {
266 DLOG(FATAL) << "Unable to start sqlite3_backup().";
267 return false;
268 }
269
270 // -1 backs up the entire database.
271 int rc = sqlite3_backup_step(backup, -1);
272 int pages = sqlite3_backup_pagecount(backup);
273 sqlite3_backup_finish(backup);
274
275 // The destination database was locked.
276 if (rc == SQLITE_BUSY) {
277 return false;
278 }
279
280 // The entire database should have been backed up.
281 if (rc != SQLITE_DONE) {
282 DLOG(FATAL) << "Unable to copy entire null database.";
283 return false;
284 }
285
286 // Exactly one page should have been backed up. If this breaks,
287 // check this function to make sure assumptions aren't being broken.
288 DCHECK_EQ(pages, 1);
289
290 return true;
291}
292
293bool Connection::RazeWithTimout(base::TimeDelta timeout) {
294 if (!db_) {
295 DLOG(FATAL) << "Cannot raze null db";
296 return false;
297 }
298
299 ScopedBusyTimeout busy_timeout(db_);
300 busy_timeout.SetTimeout(timeout);
301 return Raze();
302}
303
[email protected]e5ffd0e42009-09-11 21:30:56304bool Connection::BeginTransaction() {
305 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33306 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56307
308 // When we're going to rollback, fail on this begin and don't actually
309 // mark us as entering the nested transaction.
310 return false;
311 }
312
313 bool success = true;
314 if (!transaction_nesting_) {
315 needs_rollback_ = false;
316
317 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:59318 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56319 return false;
320 }
321 transaction_nesting_++;
322 return success;
323}
324
325void Connection::RollbackTransaction() {
326 if (!transaction_nesting_) {
[email protected]eff1fa522011-12-12 23:50:59327 DLOG(FATAL) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56328 return;
329 }
330
331 transaction_nesting_--;
332
333 if (transaction_nesting_ > 0) {
334 // Mark the outermost transaction as needing rollback.
335 needs_rollback_ = true;
336 return;
337 }
338
339 DoRollback();
340}
341
342bool Connection::CommitTransaction() {
343 if (!transaction_nesting_) {
[email protected]eff1fa522011-12-12 23:50:59344 DLOG(FATAL) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56345 return false;
346 }
347 transaction_nesting_--;
348
349 if (transaction_nesting_ > 0) {
350 // Mark any nested transactions as failing after we've already got one.
351 return !needs_rollback_;
352 }
353
354 if (needs_rollback_) {
355 DoRollback();
356 return false;
357 }
358
359 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
[email protected]e5ffd0e42009-09-11 21:30:56360 return commit.Run();
361}
362
[email protected]eff1fa522011-12-12 23:50:59363int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50364 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56365 if (!db_)
366 return false;
[email protected]eff1fa522011-12-12 23:50:59367 return sqlite3_exec(db_, sql, NULL, NULL, NULL);
368}
369
370bool Connection::Execute(const char* sql) {
371 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:00372 if (error != SQLITE_OK)
373 error = OnSqliteError(error, NULL);
374
[email protected]28fe0ff2012-02-25 00:40:33375 // This needs to be a FATAL log because the error case of arriving here is
376 // that there's a malformed SQL statement. This can arise in development if
377 // a change alters the schema but not all queries adjust.
[email protected]eff1fa522011-12-12 23:50:59378 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:33379 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:59380 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:56381}
382
[email protected]5b96f3772010-09-28 16:30:57383bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
384 if (!db_)
385 return false;
386
387 ScopedBusyTimeout busy_timeout(db_);
388 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:59389 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:57390}
391
[email protected]e5ffd0e42009-09-11 21:30:56392bool Connection::HasCachedStatement(const StatementID& id) const {
393 return statement_cache_.find(id) != statement_cache_.end();
394}
395
396scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
397 const StatementID& id,
398 const char* sql) {
399 CachedStatementMap::iterator i = statement_cache_.find(id);
400 if (i != statement_cache_.end()) {
401 // Statement is in the cache. It should still be active (we're the only
402 // one invalidating cached statements, and we'll remove it from the cache
403 // if we do that. Make sure we reset it before giving out the cached one in
404 // case it still has some stuff bound.
405 DCHECK(i->second->is_valid());
406 sqlite3_reset(i->second->stmt());
407 return i->second;
408 }
409
410 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
411 if (statement->is_valid())
412 statement_cache_[id] = statement; // Only cache valid statements.
413 return statement;
414}
415
416scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
417 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50418 AssertIOAllowed();
419
[email protected]e5ffd0e42009-09-11 21:30:56420 if (!db_)
[email protected]2eec0a22012-07-24 01:59:58421 return new StatementRef(); // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:56422
423 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:00424 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
425 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:59426 // This is evidence of a syntax error in the incoming SQL.
427 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:00428
429 // It could also be database corruption.
430 OnSqliteError(rc, NULL);
[email protected]2eec0a22012-07-24 01:59:58431 return new StatementRef();
[email protected]e5ffd0e42009-09-11 21:30:56432 }
433 return new StatementRef(this, stmt);
434}
435
[email protected]2eec0a22012-07-24 01:59:58436scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
437 const char* sql) const {
438 if (!db_)
439 return new StatementRef(); // Return inactive statement.
440
441 sqlite3_stmt* stmt = NULL;
442 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
443 if (rc != SQLITE_OK) {
444 // This is evidence of a syntax error in the incoming SQL.
445 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
446 return new StatementRef();
447 }
448 return new StatementRef(stmt);
449}
450
[email protected]eff1fa522011-12-12 23:50:59451bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50452 AssertIOAllowed();
[email protected]eff1fa522011-12-12 23:50:59453 sqlite3_stmt* stmt = NULL;
454 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
455 return false;
456
457 sqlite3_finalize(stmt);
458 return true;
459}
460
[email protected]1ed78a32009-09-15 20:24:17461bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:53462 return DoesTableOrIndexExist(table_name, "table");
463}
464
465bool Connection::DoesIndexExist(const char* index_name) const {
466 return DoesTableOrIndexExist(index_name, "index");
467}
468
469bool Connection::DoesTableOrIndexExist(
470 const char* name, const char* type) const {
[email protected]2eec0a22012-07-24 01:59:58471 const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?";
472 Statement statement(GetUntrackedStatement(kSql));
[email protected]e2cadec82011-12-13 02:00:53473 statement.BindString(0, type);
474 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:33475
[email protected]e5ffd0e42009-09-11 21:30:56476 return statement.Step(); // Table exists if any row was returned.
477}
478
479bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:17480 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:56481 std::string sql("PRAGMA TABLE_INFO(");
482 sql.append(table_name);
483 sql.append(")");
484
[email protected]2eec0a22012-07-24 01:59:58485 Statement statement(GetUntrackedStatement(sql.c_str()));
[email protected]e5ffd0e42009-09-11 21:30:56486 while (statement.Step()) {
487 if (!statement.ColumnString(1).compare(column_name))
488 return true;
489 }
490 return false;
491}
492
493int64 Connection::GetLastInsertRowId() const {
494 if (!db_) {
[email protected]eff1fa522011-12-12 23:50:59495 DLOG(FATAL) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:56496 return 0;
497 }
498 return sqlite3_last_insert_rowid(db_);
499}
500
[email protected]1ed78a32009-09-15 20:24:17501int Connection::GetLastChangeCount() const {
502 if (!db_) {
[email protected]eff1fa522011-12-12 23:50:59503 DLOG(FATAL) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:17504 return 0;
505 }
506 return sqlite3_changes(db_);
507}
508
[email protected]e5ffd0e42009-09-11 21:30:56509int Connection::GetErrorCode() const {
510 if (!db_)
511 return SQLITE_ERROR;
512 return sqlite3_errcode(db_);
513}
514
[email protected]767718e52010-09-21 23:18:49515int Connection::GetLastErrno() const {
516 if (!db_)
517 return -1;
518
519 int err = 0;
520 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
521 return -2;
522
523 return err;
524}
525
[email protected]e5ffd0e42009-09-11 21:30:56526const char* Connection::GetErrorMessage() const {
527 if (!db_)
528 return "sql::Connection has no connection.";
529 return sqlite3_errmsg(db_);
530}
531
[email protected]765b44502009-10-02 05:01:42532bool Connection::OpenInternal(const std::string& file_name) {
[email protected]35f7e5392012-07-27 19:54:50533 AssertIOAllowed();
534
[email protected]9cfbc922009-11-17 20:13:17535 if (db_) {
[email protected]eff1fa522011-12-12 23:50:59536 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:17537 return false;
538 }
539
[email protected]765b44502009-10-02 05:01:42540 int err = sqlite3_open(file_name.c_str(), &db_);
541 if (err != SQLITE_OK) {
[email protected]bd2ccdb4a2012-12-07 22:14:50542 // Histogram failures specific to initial open for debugging
543 // purposes.
544 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err & 0xff, 50);
545
[email protected]765b44502009-10-02 05:01:42546 OnSqliteError(err, NULL);
[email protected]64021042012-02-10 20:02:29547 Close();
[email protected]765b44502009-10-02 05:01:42548 db_ = NULL;
549 return false;
550 }
551
[email protected]bd2ccdb4a2012-12-07 22:14:50552 // sqlite3_open() does not actually read the database file (unless a
553 // hot journal is found). Successfully executing this pragma on an
554 // existing database requires a valid header on page 1.
555 // TODO(shess): For now, just probing to see what the lay of the
556 // land is. If it's mostly SQLITE_NOTADB, then the database should
557 // be razed.
558 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
559 if (err != SQLITE_OK)
560 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err & 0xff, 50);
561
[email protected]658f8332010-09-18 04:40:43562 // Enable extended result codes to provide more color on I/O errors.
563 // Not having extended result codes is not a fatal problem, as
564 // Chromium code does not attempt to handle I/O errors anyhow. The
565 // current implementation always returns SQLITE_OK, the DCHECK is to
566 // quickly notify someone if SQLite changes.
567 err = sqlite3_extended_result_codes(db_, 1);
568 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
569
[email protected]5b96f3772010-09-28 16:30:57570 // If indicated, lock up the database before doing anything else, so
571 // that the following code doesn't have to deal with locking.
572 // TODO(shess): This code is brittle. Find the cases where code
573 // doesn't request |exclusive_locking_| and audit that it does the
574 // right thing with SQLITE_BUSY, and that it doesn't make
575 // assumptions about who might change things in the database.
576 // http://crbug.com/56559
577 if (exclusive_locking_) {
578 // TODO(shess): This should probably be a full CHECK(). Code
579 // which requests exclusive locking but doesn't get it is almost
580 // certain to be ill-tested.
581 if (!Execute("PRAGMA locking_mode=EXCLUSIVE"))
[email protected]eff1fa522011-12-12 23:50:59582 DLOG(FATAL) << "Could not set locking mode: " << GetErrorMessage();
[email protected]5b96f3772010-09-28 16:30:57583 }
584
[email protected]4e179ba2012-03-17 16:06:47585 // http://www.sqlite.org/pragma.html#pragma_journal_mode
586 // DELETE (default) - delete -journal file to commit.
587 // TRUNCATE - truncate -journal file to commit.
588 // PERSIST - zero out header of -journal file to commit.
589 // journal_size_limit provides size to trim to in PERSIST.
590 // TODO(shess): Figure out if PERSIST and journal_size_limit really
591 // matter. In theory, it keeps pages pre-allocated, so if
592 // transactions usually fit, it should be faster.
593 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
594 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
595
[email protected]c68ce172011-11-24 22:30:27596 const base::TimeDelta kBusyTimeout =
597 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
598
[email protected]765b44502009-10-02 05:01:42599 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57600 // Enforce SQLite restrictions on |page_size_|.
601 DCHECK(!(page_size_ & (page_size_ - 1)))
602 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:24603 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:57604 DCHECK_LE(page_size_, kSqliteMaxPageSize);
605 const std::string sql = StringPrintf("PRAGMA page_size=%d", page_size_);
606 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59607 DLOG(FATAL) << "Could not set page size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42608 }
609
610 if (cache_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57611 const std::string sql = StringPrintf("PRAGMA cache_size=%d", cache_size_);
612 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59613 DLOG(FATAL) << "Could not set cache size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42614 }
615
[email protected]6e0b1442011-08-09 23:23:58616 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]eff1fa522011-12-12 23:50:59617 DLOG(FATAL) << "Could not enable secure_delete: " << GetErrorMessage();
[email protected]6e0b1442011-08-09 23:23:58618 Close();
619 return false;
620 }
621
[email protected]765b44502009-10-02 05:01:42622 return true;
623}
624
[email protected]e5ffd0e42009-09-11 21:30:56625void Connection::DoRollback() {
626 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
[email protected]eff1fa522011-12-12 23:50:59627 rollback.Run();
[email protected]44ad7d902012-03-23 00:09:05628 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:56629}
630
631void Connection::StatementRefCreated(StatementRef* ref) {
632 DCHECK(open_statements_.find(ref) == open_statements_.end());
633 open_statements_.insert(ref);
634}
635
636void Connection::StatementRefDeleted(StatementRef* ref) {
637 StatementRefSet::iterator i = open_statements_.find(ref);
638 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:59639 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:56640 else
641 open_statements_.erase(i);
642}
643
644void Connection::ClearCache() {
645 statement_cache_.clear();
646
647 // The cache clear will get most statements. There may be still be references
648 // to some statements that are held by others (including one-shot statements).
649 // This will deactivate them so they can't be used again.
650 for (StatementRefSet::iterator i = open_statements_.begin();
651 i != open_statements_.end(); ++i)
652 (*i)->Close();
653}
654
[email protected]faa604e2009-09-25 22:38:59655int Connection::OnSqliteError(int err, sql::Statement *stmt) {
[email protected]c088e3a32013-01-03 23:59:14656 // Strip extended error codes.
657 int base_err = err&0xff;
658
659 static size_t kSqliteErrorMax = 50;
660 UMA_HISTOGRAM_ENUMERATION("Sqlite.Error", base_err, kSqliteErrorMax);
661 if (!error_histogram_name_.empty()) {
662 // TODO(shess): The histogram macros create a bit of static
663 // storage for caching the histogram object. Since SQLite is
664 // being used for I/O, generally without error, this code
665 // shouldn't execute often enough for such caching to be crucial.
666 // If it becomes an issue, the object could be cached alongside
667 // error_histogram_name_.
[email protected]de415552013-01-23 04:12:17668 base::HistogramBase* histogram =
[email protected]c088e3a32013-01-03 23:59:14669 base::LinearHistogram::FactoryGet(
670 error_histogram_name_, 1, kSqliteErrorMax, kSqliteErrorMax + 1,
[email protected]de415552013-01-23 04:12:17671 base::HistogramBase::kUmaTargetedHistogramFlag);
[email protected]c088e3a32013-01-03 23:59:14672 if (histogram)
673 histogram->Add(base_err);
674 }
675
676 // Always log the error.
677 LOG(ERROR) << "sqlite error " << err
678 << ", errno " << GetLastErrno()
679 << ": " << GetErrorMessage();
680
[email protected]faa604e2009-09-25 22:38:59681 if (error_delegate_.get())
682 return error_delegate_->OnError(err, this, stmt);
[email protected]c088e3a32013-01-03 23:59:14683
[email protected]faa604e2009-09-25 22:38:59684 // The default handling is to assert on debug and to ignore on release.
[email protected]eff1fa522011-12-12 23:50:59685 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:59686 return err;
687}
688
[email protected]e5ffd0e42009-09-11 21:30:56689} // namespace sql