blob: 93d0695ad3db5668168ab1be2b4664b9930ed4c8 [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"
11#include "base/string_util.h"
[email protected]f0a54b22011-07-19 18:40:2112#include "base/stringprintf.h"
[email protected]d55194ca2010-03-11 18:25:4513#include "base/utf_string_conversions.h"
[email protected]f0a54b22011-07-19 18:40:2114#include "sql/statement.h"
[email protected]e33cba42010-08-18 23:37:0315#include "third_party/sqlite/sqlite3.h"
[email protected]e5ffd0e42009-09-11 21:30:5616
[email protected]5b96f3772010-09-28 16:30:5717namespace {
18
19// Spin for up to a second waiting for the lock to clear when setting
20// up the database.
21// TODO(shess): Better story on this. http://crbug.com/56559
[email protected]c68ce172011-11-24 22:30:2722const int kBusyTimeoutSeconds = 1;
[email protected]5b96f3772010-09-28 16:30:5723
24class ScopedBusyTimeout {
25 public:
26 explicit ScopedBusyTimeout(sqlite3* db)
27 : db_(db) {
28 }
29 ~ScopedBusyTimeout() {
30 sqlite3_busy_timeout(db_, 0);
31 }
32
33 int SetTimeout(base::TimeDelta timeout) {
34 DCHECK_LT(timeout.InMilliseconds(), INT_MAX);
35 return sqlite3_busy_timeout(db_,
36 static_cast<int>(timeout.InMilliseconds()));
37 }
38
39 private:
40 sqlite3* db_;
41};
42
[email protected]6d42f152012-11-10 00:38:2443// Helper to "safely" enable writable_schema. No error checking
44// because it is reasonable to just forge ahead in case of an error.
45// If turning it on fails, then most likely nothing will work, whereas
46// if turning it off fails, it only matters if some code attempts to
47// continue working with the database and tries to modify the
48// sqlite_master table (none of our code does this).
49class ScopedWritableSchema {
50 public:
51 explicit ScopedWritableSchema(sqlite3* db)
52 : db_(db) {
53 sqlite3_exec(db_, "PRAGMA writable_schema=1", NULL, NULL, NULL);
54 }
55 ~ScopedWritableSchema() {
56 sqlite3_exec(db_, "PRAGMA writable_schema=0", NULL, NULL, NULL);
57 }
58
59 private:
60 sqlite3* db_;
61};
62
[email protected]5b96f3772010-09-28 16:30:5763} // namespace
64
[email protected]e5ffd0e42009-09-11 21:30:5665namespace sql {
66
67bool StatementID::operator<(const StatementID& other) const {
68 if (number_ != other.number_)
69 return number_ < other.number_;
70 return strcmp(str_, other.str_) < 0;
71}
72
[email protected]d4799a32010-09-28 22:54:5873ErrorDelegate::~ErrorDelegate() {
74}
75
[email protected]e5ffd0e42009-09-11 21:30:5676Connection::StatementRef::StatementRef()
77 : connection_(NULL),
78 stmt_(NULL) {
79}
80
[email protected]2eec0a22012-07-24 01:59:5881Connection::StatementRef::StatementRef(sqlite3_stmt* stmt)
82 : connection_(NULL),
83 stmt_(stmt) {
84}
85
[email protected]e5ffd0e42009-09-11 21:30:5686Connection::StatementRef::StatementRef(Connection* connection,
87 sqlite3_stmt* stmt)
88 : connection_(connection),
89 stmt_(stmt) {
90 connection_->StatementRefCreated(this);
91}
92
93Connection::StatementRef::~StatementRef() {
94 if (connection_)
95 connection_->StatementRefDeleted(this);
96 Close();
97}
98
99void Connection::StatementRef::Close() {
100 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:50101 // Call to AssertIOAllowed() cannot go at the beginning of the function
102 // because Close() is called unconditionally from destructor to clean
103 // connection_. And if this is inactive statement this won't cause any
104 // disk access and destructor most probably will be called on thread
105 // not allowing disk access.
106 // TODO([email protected]): This should move to the beginning
107 // of the function. http://crbug.com/136655.
108 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56109 sqlite3_finalize(stmt_);
110 stmt_ = NULL;
111 }
112 connection_ = NULL; // The connection may be getting deleted.
113}
114
115Connection::Connection()
116 : db_(NULL),
117 page_size_(0),
118 cache_size_(0),
119 exclusive_locking_(false),
120 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50121 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16122 in_memory_(false),
123 error_delegate_(NULL) {
[email protected]e5ffd0e42009-09-11 21:30:56124}
125
126Connection::~Connection() {
127 Close();
128}
129
[email protected]765b44502009-10-02 05:01:42130bool Connection::Open(const FilePath& path) {
[email protected]e5ffd0e42009-09-11 21:30:56131#if defined(OS_WIN)
[email protected]765b44502009-10-02 05:01:42132 return OpenInternal(WideToUTF8(path.value()));
[email protected]e5ffd0e42009-09-11 21:30:56133#elif defined(OS_POSIX)
[email protected]765b44502009-10-02 05:01:42134 return OpenInternal(path.value());
[email protected]e5ffd0e42009-09-11 21:30:56135#endif
[email protected]765b44502009-10-02 05:01:42136}
[email protected]e5ffd0e42009-09-11 21:30:56137
[email protected]765b44502009-10-02 05:01:42138bool Connection::OpenInMemory() {
[email protected]35f7e5392012-07-27 19:54:50139 in_memory_ = true;
[email protected]765b44502009-10-02 05:01:42140 return OpenInternal(":memory:");
[email protected]e5ffd0e42009-09-11 21:30:56141}
142
143void Connection::Close() {
[email protected]4e179ba2012-03-17 16:06:47144 // TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
145 // will delete the -journal file. For ChromiumOS or other more
146 // embedded systems, this is probably not appropriate, whereas on
147 // desktop it might make some sense.
148
[email protected]4b350052012-02-24 20:40:48149 // sqlite3_close() needs all prepared statements to be finalized.
150 // Release all cached statements, then assert that the client has
151 // released all statements.
[email protected]e5ffd0e42009-09-11 21:30:56152 statement_cache_.clear();
153 DCHECK(open_statements_.empty());
[email protected]4b350052012-02-24 20:40:48154
155 // Additionally clear the prepared statements, because they contain
156 // weak references to this connection. This case has come up when
157 // error-handling code is hit in production.
158 ClearCache();
159
[email protected]e5ffd0e42009-09-11 21:30:56160 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50161 // Call to AssertIOAllowed() cannot go at the beginning of the function
162 // because Close() must be called from destructor to clean
163 // statement_cache_, it won't cause any disk access and it most probably
164 // will happen on thread not allowing disk access.
165 // TODO([email protected]): This should move to the beginning
166 // of the function. http://crbug.com/136655.
167 AssertIOAllowed();
[email protected]4b350052012-02-24 20:40:48168 // TODO(shess): Histogram for failure.
[email protected]e5ffd0e42009-09-11 21:30:56169 sqlite3_close(db_);
170 db_ = NULL;
171 }
172}
173
174void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50175 AssertIOAllowed();
176
[email protected]e5ffd0e42009-09-11 21:30:56177 if (!db_) {
[email protected]eff1fa522011-12-12 23:50:59178 DLOG(FATAL) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56179 return;
180 }
181
182 // A statement must be open for the preload command to work. If the meta
183 // table doesn't exist, it probably means this is a new database and there
184 // is nothing to preload (so it's OK we do nothing).
185 if (!DoesTableExist("meta"))
186 return;
187 Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
[email protected]eff1fa522011-12-12 23:50:59188 if (!dummy.Step())
[email protected]e5ffd0e42009-09-11 21:30:56189 return;
190
[email protected]4176eee4b2011-01-26 14:33:32191#if !defined(USE_SYSTEM_SQLITE)
192 // This function is only defined in Chromium's version of sqlite.
193 // Do not call it when using system sqlite.
[email protected]67361b32011-04-12 20:13:06194 sqlite3_preload(db_);
[email protected]4176eee4b2011-01-26 14:33:32195#endif
[email protected]e5ffd0e42009-09-11 21:30:56196}
197
[email protected]8e0c01282012-04-06 19:36:49198// Create an in-memory database with the existing database's page
199// size, then backup that database over the existing database.
200bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50201 AssertIOAllowed();
202
[email protected]8e0c01282012-04-06 19:36:49203 if (!db_) {
204 DLOG(FATAL) << "Cannot raze null db";
205 return false;
206 }
207
208 if (transaction_nesting_ > 0) {
209 DLOG(FATAL) << "Cannot raze within a transaction";
210 return false;
211 }
212
213 sql::Connection null_db;
214 if (!null_db.OpenInMemory()) {
215 DLOG(FATAL) << "Unable to open in-memory database.";
216 return false;
217 }
218
[email protected]6d42f152012-11-10 00:38:24219 if (page_size_) {
220 // Enforce SQLite restrictions on |page_size_|.
221 DCHECK(!(page_size_ & (page_size_ - 1)))
222 << " page_size_ " << page_size_ << " is not a power of two.";
223 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
224 DCHECK_LE(page_size_, kSqliteMaxPageSize);
225 const std::string sql = StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:42226 if (!null_db.Execute(sql.c_str()))
227 return false;
228 }
229
[email protected]6d42f152012-11-10 00:38:24230#if defined(OS_ANDROID)
231 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
232 // in-memory databases do not respect this define.
233 // TODO(shess): Figure out a way to set this without using platform
234 // specific code. AFAICT from sqlite3.c, the only way to do it
235 // would be to create an actual filesystem database, which is
236 // unfortunate.
237 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
238 return false;
239#endif
[email protected]8e0c01282012-04-06 19:36:49240
241 // The page size doesn't take effect until a database has pages, and
242 // at this point the null database has none. Changing the schema
243 // version will create the first page. This will not affect the
244 // schema version in the resulting database, as SQLite's backup
245 // implementation propagates the schema version from the original
246 // connection to the new version of the database, incremented by one
247 // so that other readers see the schema change and act accordingly.
248 if (!null_db.Execute("PRAGMA schema_version = 1"))
249 return false;
250
[email protected]6d42f152012-11-10 00:38:24251 // SQLite tracks the expected number of database pages in the first
252 // page, and if it does not match the total retrieved from a
253 // filesystem call, treats the database as corrupt. This situation
254 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
255 // used to hint to SQLite to soldier on in that case, specifically
256 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
257 // sqlite3.c lockBtree().]
258 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
259 // page_size" can be used to query such a database.
260 ScopedWritableSchema writable_schema(db_);
261
[email protected]8e0c01282012-04-06 19:36:49262 sqlite3_backup* backup = sqlite3_backup_init(db_, "main",
263 null_db.db_, "main");
264 if (!backup) {
265 DLOG(FATAL) << "Unable to start sqlite3_backup().";
266 return false;
267 }
268
269 // -1 backs up the entire database.
270 int rc = sqlite3_backup_step(backup, -1);
271 int pages = sqlite3_backup_pagecount(backup);
272 sqlite3_backup_finish(backup);
273
274 // The destination database was locked.
275 if (rc == SQLITE_BUSY) {
276 return false;
277 }
278
279 // The entire database should have been backed up.
280 if (rc != SQLITE_DONE) {
281 DLOG(FATAL) << "Unable to copy entire null database.";
282 return false;
283 }
284
285 // Exactly one page should have been backed up. If this breaks,
286 // check this function to make sure assumptions aren't being broken.
287 DCHECK_EQ(pages, 1);
288
289 return true;
290}
291
292bool Connection::RazeWithTimout(base::TimeDelta timeout) {
293 if (!db_) {
294 DLOG(FATAL) << "Cannot raze null db";
295 return false;
296 }
297
298 ScopedBusyTimeout busy_timeout(db_);
299 busy_timeout.SetTimeout(timeout);
300 return Raze();
301}
302
[email protected]e5ffd0e42009-09-11 21:30:56303bool Connection::BeginTransaction() {
304 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33305 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56306
307 // When we're going to rollback, fail on this begin and don't actually
308 // mark us as entering the nested transaction.
309 return false;
310 }
311
312 bool success = true;
313 if (!transaction_nesting_) {
314 needs_rollback_ = false;
315
316 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:59317 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56318 return false;
319 }
320 transaction_nesting_++;
321 return success;
322}
323
324void Connection::RollbackTransaction() {
325 if (!transaction_nesting_) {
[email protected]eff1fa522011-12-12 23:50:59326 DLOG(FATAL) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56327 return;
328 }
329
330 transaction_nesting_--;
331
332 if (transaction_nesting_ > 0) {
333 // Mark the outermost transaction as needing rollback.
334 needs_rollback_ = true;
335 return;
336 }
337
338 DoRollback();
339}
340
341bool Connection::CommitTransaction() {
342 if (!transaction_nesting_) {
[email protected]eff1fa522011-12-12 23:50:59343 DLOG(FATAL) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56344 return false;
345 }
346 transaction_nesting_--;
347
348 if (transaction_nesting_ > 0) {
349 // Mark any nested transactions as failing after we've already got one.
350 return !needs_rollback_;
351 }
352
353 if (needs_rollback_) {
354 DoRollback();
355 return false;
356 }
357
358 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
[email protected]e5ffd0e42009-09-11 21:30:56359 return commit.Run();
360}
361
[email protected]eff1fa522011-12-12 23:50:59362int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50363 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56364 if (!db_)
365 return false;
[email protected]eff1fa522011-12-12 23:50:59366 return sqlite3_exec(db_, sql, NULL, NULL, NULL);
367}
368
369bool Connection::Execute(const char* sql) {
370 int error = ExecuteAndReturnErrorCode(sql);
[email protected]28fe0ff2012-02-25 00:40:33371 // This needs to be a FATAL log because the error case of arriving here is
372 // that there's a malformed SQL statement. This can arise in development if
373 // a change alters the schema but not all queries adjust.
[email protected]eff1fa522011-12-12 23:50:59374 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:33375 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:59376 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:56377}
378
[email protected]5b96f3772010-09-28 16:30:57379bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
380 if (!db_)
381 return false;
382
383 ScopedBusyTimeout busy_timeout(db_);
384 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:59385 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:57386}
387
[email protected]e5ffd0e42009-09-11 21:30:56388bool Connection::HasCachedStatement(const StatementID& id) const {
389 return statement_cache_.find(id) != statement_cache_.end();
390}
391
392scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
393 const StatementID& id,
394 const char* sql) {
395 CachedStatementMap::iterator i = statement_cache_.find(id);
396 if (i != statement_cache_.end()) {
397 // Statement is in the cache. It should still be active (we're the only
398 // one invalidating cached statements, and we'll remove it from the cache
399 // if we do that. Make sure we reset it before giving out the cached one in
400 // case it still has some stuff bound.
401 DCHECK(i->second->is_valid());
402 sqlite3_reset(i->second->stmt());
403 return i->second;
404 }
405
406 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
407 if (statement->is_valid())
408 statement_cache_[id] = statement; // Only cache valid statements.
409 return statement;
410}
411
412scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
413 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50414 AssertIOAllowed();
415
[email protected]e5ffd0e42009-09-11 21:30:56416 if (!db_)
[email protected]2eec0a22012-07-24 01:59:58417 return new StatementRef(); // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:56418
419 sqlite3_stmt* stmt = NULL;
420 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:59421 // This is evidence of a syntax error in the incoming SQL.
422 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]2eec0a22012-07-24 01:59:58423 return new StatementRef();
[email protected]e5ffd0e42009-09-11 21:30:56424 }
425 return new StatementRef(this, stmt);
426}
427
[email protected]2eec0a22012-07-24 01:59:58428scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
429 const char* sql) const {
430 if (!db_)
431 return new StatementRef(); // Return inactive statement.
432
433 sqlite3_stmt* stmt = NULL;
434 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
435 if (rc != SQLITE_OK) {
436 // This is evidence of a syntax error in the incoming SQL.
437 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
438 return new StatementRef();
439 }
440 return new StatementRef(stmt);
441}
442
[email protected]eff1fa522011-12-12 23:50:59443bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50444 AssertIOAllowed();
[email protected]eff1fa522011-12-12 23:50:59445 sqlite3_stmt* stmt = NULL;
446 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
447 return false;
448
449 sqlite3_finalize(stmt);
450 return true;
451}
452
[email protected]1ed78a32009-09-15 20:24:17453bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:53454 return DoesTableOrIndexExist(table_name, "table");
455}
456
457bool Connection::DoesIndexExist(const char* index_name) const {
458 return DoesTableOrIndexExist(index_name, "index");
459}
460
461bool Connection::DoesTableOrIndexExist(
462 const char* name, const char* type) const {
[email protected]2eec0a22012-07-24 01:59:58463 const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?";
464 Statement statement(GetUntrackedStatement(kSql));
[email protected]e2cadec82011-12-13 02:00:53465 statement.BindString(0, type);
466 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:33467
[email protected]e5ffd0e42009-09-11 21:30:56468 return statement.Step(); // Table exists if any row was returned.
469}
470
471bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:17472 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:56473 std::string sql("PRAGMA TABLE_INFO(");
474 sql.append(table_name);
475 sql.append(")");
476
[email protected]2eec0a22012-07-24 01:59:58477 Statement statement(GetUntrackedStatement(sql.c_str()));
[email protected]e5ffd0e42009-09-11 21:30:56478 while (statement.Step()) {
479 if (!statement.ColumnString(1).compare(column_name))
480 return true;
481 }
482 return false;
483}
484
485int64 Connection::GetLastInsertRowId() const {
486 if (!db_) {
[email protected]eff1fa522011-12-12 23:50:59487 DLOG(FATAL) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:56488 return 0;
489 }
490 return sqlite3_last_insert_rowid(db_);
491}
492
[email protected]1ed78a32009-09-15 20:24:17493int Connection::GetLastChangeCount() const {
494 if (!db_) {
[email protected]eff1fa522011-12-12 23:50:59495 DLOG(FATAL) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:17496 return 0;
497 }
498 return sqlite3_changes(db_);
499}
500
[email protected]e5ffd0e42009-09-11 21:30:56501int Connection::GetErrorCode() const {
502 if (!db_)
503 return SQLITE_ERROR;
504 return sqlite3_errcode(db_);
505}
506
[email protected]767718e52010-09-21 23:18:49507int Connection::GetLastErrno() const {
508 if (!db_)
509 return -1;
510
511 int err = 0;
512 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
513 return -2;
514
515 return err;
516}
517
[email protected]e5ffd0e42009-09-11 21:30:56518const char* Connection::GetErrorMessage() const {
519 if (!db_)
520 return "sql::Connection has no connection.";
521 return sqlite3_errmsg(db_);
522}
523
[email protected]765b44502009-10-02 05:01:42524bool Connection::OpenInternal(const std::string& file_name) {
[email protected]35f7e5392012-07-27 19:54:50525 AssertIOAllowed();
526
[email protected]9cfbc922009-11-17 20:13:17527 if (db_) {
[email protected]eff1fa522011-12-12 23:50:59528 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:17529 return false;
530 }
531
[email protected]765b44502009-10-02 05:01:42532 int err = sqlite3_open(file_name.c_str(), &db_);
533 if (err != SQLITE_OK) {
534 OnSqliteError(err, NULL);
[email protected]64021042012-02-10 20:02:29535 Close();
[email protected]765b44502009-10-02 05:01:42536 db_ = NULL;
537 return false;
538 }
539
[email protected]658f8332010-09-18 04:40:43540 // Enable extended result codes to provide more color on I/O errors.
541 // Not having extended result codes is not a fatal problem, as
542 // Chromium code does not attempt to handle I/O errors anyhow. The
543 // current implementation always returns SQLITE_OK, the DCHECK is to
544 // quickly notify someone if SQLite changes.
545 err = sqlite3_extended_result_codes(db_, 1);
546 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
547
[email protected]5b96f3772010-09-28 16:30:57548 // If indicated, lock up the database before doing anything else, so
549 // that the following code doesn't have to deal with locking.
550 // TODO(shess): This code is brittle. Find the cases where code
551 // doesn't request |exclusive_locking_| and audit that it does the
552 // right thing with SQLITE_BUSY, and that it doesn't make
553 // assumptions about who might change things in the database.
554 // http://crbug.com/56559
555 if (exclusive_locking_) {
556 // TODO(shess): This should probably be a full CHECK(). Code
557 // which requests exclusive locking but doesn't get it is almost
558 // certain to be ill-tested.
559 if (!Execute("PRAGMA locking_mode=EXCLUSIVE"))
[email protected]eff1fa522011-12-12 23:50:59560 DLOG(FATAL) << "Could not set locking mode: " << GetErrorMessage();
[email protected]5b96f3772010-09-28 16:30:57561 }
562
[email protected]4e179ba2012-03-17 16:06:47563 // http://www.sqlite.org/pragma.html#pragma_journal_mode
564 // DELETE (default) - delete -journal file to commit.
565 // TRUNCATE - truncate -journal file to commit.
566 // PERSIST - zero out header of -journal file to commit.
567 // journal_size_limit provides size to trim to in PERSIST.
568 // TODO(shess): Figure out if PERSIST and journal_size_limit really
569 // matter. In theory, it keeps pages pre-allocated, so if
570 // transactions usually fit, it should be faster.
571 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
572 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
573
[email protected]c68ce172011-11-24 22:30:27574 const base::TimeDelta kBusyTimeout =
575 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
576
[email protected]765b44502009-10-02 05:01:42577 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57578 // Enforce SQLite restrictions on |page_size_|.
579 DCHECK(!(page_size_ & (page_size_ - 1)))
580 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:24581 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:57582 DCHECK_LE(page_size_, kSqliteMaxPageSize);
583 const std::string sql = StringPrintf("PRAGMA page_size=%d", page_size_);
584 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59585 DLOG(FATAL) << "Could not set page size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42586 }
587
588 if (cache_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57589 const std::string sql = StringPrintf("PRAGMA cache_size=%d", cache_size_);
590 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59591 DLOG(FATAL) << "Could not set cache size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42592 }
593
[email protected]6e0b1442011-08-09 23:23:58594 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]eff1fa522011-12-12 23:50:59595 DLOG(FATAL) << "Could not enable secure_delete: " << GetErrorMessage();
[email protected]6e0b1442011-08-09 23:23:58596 Close();
597 return false;
598 }
599
[email protected]765b44502009-10-02 05:01:42600 return true;
601}
602
[email protected]e5ffd0e42009-09-11 21:30:56603void Connection::DoRollback() {
604 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
[email protected]eff1fa522011-12-12 23:50:59605 rollback.Run();
[email protected]44ad7d902012-03-23 00:09:05606 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:56607}
608
609void Connection::StatementRefCreated(StatementRef* ref) {
610 DCHECK(open_statements_.find(ref) == open_statements_.end());
611 open_statements_.insert(ref);
612}
613
614void Connection::StatementRefDeleted(StatementRef* ref) {
615 StatementRefSet::iterator i = open_statements_.find(ref);
616 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:59617 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:56618 else
619 open_statements_.erase(i);
620}
621
622void Connection::ClearCache() {
623 statement_cache_.clear();
624
625 // The cache clear will get most statements. There may be still be references
626 // to some statements that are held by others (including one-shot statements).
627 // This will deactivate them so they can't be used again.
628 for (StatementRefSet::iterator i = open_statements_.begin();
629 i != open_statements_.end(); ++i)
630 (*i)->Close();
631}
632
[email protected]faa604e2009-09-25 22:38:59633int Connection::OnSqliteError(int err, sql::Statement *stmt) {
634 if (error_delegate_.get())
635 return error_delegate_->OnError(err, this, stmt);
636 // The default handling is to assert on debug and to ignore on release.
[email protected]eff1fa522011-12-12 23:50:59637 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:59638 return err;
639}
640
[email protected]e5ffd0e42009-09-11 21:30:56641} // namespace sql