blob: 5f6b5906e0c136e77618bd8eb4ed8ce9bf1855df [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]e5ffd0e42009-09-11 21:30:5610#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(Connection* connection,
[email protected]41a97c812013-02-07 02:35:3878 sqlite3_stmt* stmt,
79 bool was_valid)
[email protected]e5ffd0e42009-09-11 21:30:5680 : connection_(connection),
[email protected]41a97c812013-02-07 02:35:3881 stmt_(stmt),
82 was_valid_(was_valid) {
83 if (connection)
84 connection_->StatementRefCreated(this);
[email protected]e5ffd0e42009-09-11 21:30:5685}
86
87Connection::StatementRef::~StatementRef() {
88 if (connection_)
89 connection_->StatementRefDeleted(this);
[email protected]41a97c812013-02-07 02:35:3890 Close(false);
[email protected]e5ffd0e42009-09-11 21:30:5691}
92
[email protected]41a97c812013-02-07 02:35:3893void Connection::StatementRef::Close(bool forced) {
[email protected]e5ffd0e42009-09-11 21:30:5694 if (stmt_) {
[email protected]35f7e5392012-07-27 19:54:5095 // Call to AssertIOAllowed() cannot go at the beginning of the function
96 // because Close() is called unconditionally from destructor to clean
97 // connection_. And if this is inactive statement this won't cause any
98 // disk access and destructor most probably will be called on thread
99 // not allowing disk access.
100 // TODO([email protected]): This should move to the beginning
101 // of the function. http://crbug.com/136655.
102 AssertIOAllowed();
[email protected]e5ffd0e42009-09-11 21:30:56103 sqlite3_finalize(stmt_);
104 stmt_ = NULL;
105 }
106 connection_ = NULL; // The connection may be getting deleted.
[email protected]41a97c812013-02-07 02:35:38107
108 // Forced close is expected to happen from a statement error
109 // handler. In that case maintain the sense of |was_valid_| which
110 // previously held for this ref.
111 was_valid_ = was_valid_ && forced;
[email protected]e5ffd0e42009-09-11 21:30:56112}
113
114Connection::Connection()
115 : db_(NULL),
116 page_size_(0),
117 cache_size_(0),
118 exclusive_locking_(false),
119 transaction_nesting_(0),
[email protected]35f7e5392012-07-27 19:54:50120 needs_rollback_(false),
[email protected]49dc4f22012-10-17 17:41:16121 in_memory_(false),
[email protected]41a97c812013-02-07 02:35:38122 poisoned_(false),
[email protected]49dc4f22012-10-17 17:41:16123 error_delegate_(NULL) {
[email protected]e5ffd0e42009-09-11 21:30:56124}
125
126Connection::~Connection() {
127 Close();
128}
129
[email protected]a3ef4832013-02-02 05:12:33130bool Connection::Open(const base::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
[email protected]41a97c812013-02-07 02:35:38143void Connection::CloseInternal(bool forced) {
[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.
[email protected]4b350052012-02-24 20:40:48150
[email protected]41a97c812013-02-07 02:35:38151 // Release cached statements.
152 statement_cache_.clear();
153
154 // With cached statements released, in-use statements will remain.
155 // Closing the database while statements are in use is an API
156 // violation, except for forced close (which happens from within a
157 // statement's error handler).
158 DCHECK(forced || open_statements_.empty());
159
160 // Deactivate any outstanding statements so sqlite3_close() works.
161 for (StatementRefSet::iterator i = open_statements_.begin();
162 i != open_statements_.end(); ++i)
163 (*i)->Close(forced);
164 open_statements_.clear();
[email protected]4b350052012-02-24 20:40:48165
[email protected]e5ffd0e42009-09-11 21:30:56166 if (db_) {
[email protected]35f7e5392012-07-27 19:54:50167 // Call to AssertIOAllowed() cannot go at the beginning of the function
168 // because Close() must be called from destructor to clean
169 // statement_cache_, it won't cause any disk access and it most probably
170 // will happen on thread not allowing disk access.
171 // TODO([email protected]): This should move to the beginning
172 // of the function. http://crbug.com/136655.
173 AssertIOAllowed();
[email protected]4b350052012-02-24 20:40:48174 // TODO(shess): Histogram for failure.
[email protected]e5ffd0e42009-09-11 21:30:56175 sqlite3_close(db_);
176 db_ = NULL;
177 }
178}
179
[email protected]41a97c812013-02-07 02:35:38180void Connection::Close() {
181 // If the database was already closed by RazeAndClose(), then no
182 // need to close again. Clear the |poisoned_| bit so that incorrect
183 // API calls are caught.
184 if (poisoned_) {
185 poisoned_ = false;
186 return;
187 }
188
189 CloseInternal(false);
190}
191
[email protected]e5ffd0e42009-09-11 21:30:56192void Connection::Preload() {
[email protected]35f7e5392012-07-27 19:54:50193 AssertIOAllowed();
194
[email protected]e5ffd0e42009-09-11 21:30:56195 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38196 DLOG_IF(FATAL, !poisoned_) << "Cannot preload null db";
[email protected]e5ffd0e42009-09-11 21:30:56197 return;
198 }
199
200 // A statement must be open for the preload command to work. If the meta
201 // table doesn't exist, it probably means this is a new database and there
202 // is nothing to preload (so it's OK we do nothing).
203 if (!DoesTableExist("meta"))
204 return;
205 Statement dummy(GetUniqueStatement("SELECT * FROM meta"));
[email protected]eff1fa522011-12-12 23:50:59206 if (!dummy.Step())
[email protected]e5ffd0e42009-09-11 21:30:56207 return;
208
[email protected]4176eee4b2011-01-26 14:33:32209#if !defined(USE_SYSTEM_SQLITE)
210 // This function is only defined in Chromium's version of sqlite.
211 // Do not call it when using system sqlite.
[email protected]67361b32011-04-12 20:13:06212 sqlite3_preload(db_);
[email protected]4176eee4b2011-01-26 14:33:32213#endif
[email protected]e5ffd0e42009-09-11 21:30:56214}
215
[email protected]8e0c01282012-04-06 19:36:49216// Create an in-memory database with the existing database's page
217// size, then backup that database over the existing database.
218bool Connection::Raze() {
[email protected]35f7e5392012-07-27 19:54:50219 AssertIOAllowed();
220
[email protected]8e0c01282012-04-06 19:36:49221 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38222 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49223 return false;
224 }
225
226 if (transaction_nesting_ > 0) {
227 DLOG(FATAL) << "Cannot raze within a transaction";
228 return false;
229 }
230
231 sql::Connection null_db;
232 if (!null_db.OpenInMemory()) {
233 DLOG(FATAL) << "Unable to open in-memory database.";
234 return false;
235 }
236
[email protected]6d42f152012-11-10 00:38:24237 if (page_size_) {
238 // Enforce SQLite restrictions on |page_size_|.
239 DCHECK(!(page_size_ & (page_size_ - 1)))
240 << " page_size_ " << page_size_ << " is not a power of two.";
241 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
242 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04243 const std::string sql =
244 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]69c58452012-08-06 19:22:42245 if (!null_db.Execute(sql.c_str()))
246 return false;
247 }
248
[email protected]6d42f152012-11-10 00:38:24249#if defined(OS_ANDROID)
250 // Android compiles with SQLITE_DEFAULT_AUTOVACUUM. Unfortunately,
251 // in-memory databases do not respect this define.
252 // TODO(shess): Figure out a way to set this without using platform
253 // specific code. AFAICT from sqlite3.c, the only way to do it
254 // would be to create an actual filesystem database, which is
255 // unfortunate.
256 if (!null_db.Execute("PRAGMA auto_vacuum = 1"))
257 return false;
258#endif
[email protected]8e0c01282012-04-06 19:36:49259
260 // The page size doesn't take effect until a database has pages, and
261 // at this point the null database has none. Changing the schema
262 // version will create the first page. This will not affect the
263 // schema version in the resulting database, as SQLite's backup
264 // implementation propagates the schema version from the original
265 // connection to the new version of the database, incremented by one
266 // so that other readers see the schema change and act accordingly.
267 if (!null_db.Execute("PRAGMA schema_version = 1"))
268 return false;
269
[email protected]6d42f152012-11-10 00:38:24270 // SQLite tracks the expected number of database pages in the first
271 // page, and if it does not match the total retrieved from a
272 // filesystem call, treats the database as corrupt. This situation
273 // breaks almost all SQLite calls. "PRAGMA writable_schema" can be
274 // used to hint to SQLite to soldier on in that case, specifically
275 // for purposes of recovery. [See SQLITE_CORRUPT_BKPT case in
276 // sqlite3.c lockBtree().]
277 // TODO(shess): With this, "PRAGMA auto_vacuum" and "PRAGMA
278 // page_size" can be used to query such a database.
279 ScopedWritableSchema writable_schema(db_);
280
[email protected]8e0c01282012-04-06 19:36:49281 sqlite3_backup* backup = sqlite3_backup_init(db_, "main",
282 null_db.db_, "main");
283 if (!backup) {
284 DLOG(FATAL) << "Unable to start sqlite3_backup().";
285 return false;
286 }
287
288 // -1 backs up the entire database.
289 int rc = sqlite3_backup_step(backup, -1);
290 int pages = sqlite3_backup_pagecount(backup);
291 sqlite3_backup_finish(backup);
292
293 // The destination database was locked.
294 if (rc == SQLITE_BUSY) {
295 return false;
296 }
297
298 // The entire database should have been backed up.
299 if (rc != SQLITE_DONE) {
300 DLOG(FATAL) << "Unable to copy entire null database.";
301 return false;
302 }
303
304 // Exactly one page should have been backed up. If this breaks,
305 // check this function to make sure assumptions aren't being broken.
306 DCHECK_EQ(pages, 1);
307
308 return true;
309}
310
311bool Connection::RazeWithTimout(base::TimeDelta timeout) {
312 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38313 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
[email protected]8e0c01282012-04-06 19:36:49314 return false;
315 }
316
317 ScopedBusyTimeout busy_timeout(db_);
318 busy_timeout.SetTimeout(timeout);
319 return Raze();
320}
321
[email protected]41a97c812013-02-07 02:35:38322bool Connection::RazeAndClose() {
323 if (!db_) {
324 DLOG_IF(FATAL, !poisoned_) << "Cannot raze null db";
325 return false;
326 }
327
328 // Raze() cannot run in a transaction.
329 while (transaction_nesting_) {
330 RollbackTransaction();
331 }
332
333 bool result = Raze();
334
335 CloseInternal(true);
336
337 // Mark the database so that future API calls fail appropriately,
338 // but don't DCHECK (because after calling this function they are
339 // expected to fail).
340 poisoned_ = true;
341
342 return result;
343}
344
[email protected]e5ffd0e42009-09-11 21:30:56345bool Connection::BeginTransaction() {
346 if (needs_rollback_) {
[email protected]88563f62011-03-13 22:13:33347 DCHECK_GT(transaction_nesting_, 0);
[email protected]e5ffd0e42009-09-11 21:30:56348
349 // When we're going to rollback, fail on this begin and don't actually
350 // mark us as entering the nested transaction.
351 return false;
352 }
353
354 bool success = true;
355 if (!transaction_nesting_) {
356 needs_rollback_ = false;
357
358 Statement begin(GetCachedStatement(SQL_FROM_HERE, "BEGIN TRANSACTION"));
[email protected]eff1fa522011-12-12 23:50:59359 if (!begin.Run())
[email protected]e5ffd0e42009-09-11 21:30:56360 return false;
361 }
362 transaction_nesting_++;
363 return success;
364}
365
366void Connection::RollbackTransaction() {
367 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38368 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56369 return;
370 }
371
372 transaction_nesting_--;
373
374 if (transaction_nesting_ > 0) {
375 // Mark the outermost transaction as needing rollback.
376 needs_rollback_ = true;
377 return;
378 }
379
380 DoRollback();
381}
382
383bool Connection::CommitTransaction() {
384 if (!transaction_nesting_) {
[email protected]41a97c812013-02-07 02:35:38385 DLOG_IF(FATAL, !poisoned_) << "Rolling back a nonexistent transaction";
[email protected]e5ffd0e42009-09-11 21:30:56386 return false;
387 }
388 transaction_nesting_--;
389
390 if (transaction_nesting_ > 0) {
391 // Mark any nested transactions as failing after we've already got one.
392 return !needs_rollback_;
393 }
394
395 if (needs_rollback_) {
396 DoRollback();
397 return false;
398 }
399
400 Statement commit(GetCachedStatement(SQL_FROM_HERE, "COMMIT"));
[email protected]e5ffd0e42009-09-11 21:30:56401 return commit.Run();
402}
403
[email protected]eff1fa522011-12-12 23:50:59404int Connection::ExecuteAndReturnErrorCode(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50405 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38406 if (!db_) {
407 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
408 return SQLITE_ERROR;
409 }
[email protected]eff1fa522011-12-12 23:50:59410 return sqlite3_exec(db_, sql, NULL, NULL, NULL);
411}
412
413bool Connection::Execute(const char* sql) {
[email protected]41a97c812013-02-07 02:35:38414 if (!db_) {
415 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
416 return false;
417 }
418
[email protected]eff1fa522011-12-12 23:50:59419 int error = ExecuteAndReturnErrorCode(sql);
[email protected]473ad792012-11-10 00:55:00420 if (error != SQLITE_OK)
421 error = OnSqliteError(error, NULL);
422
[email protected]28fe0ff2012-02-25 00:40:33423 // This needs to be a FATAL log because the error case of arriving here is
424 // that there's a malformed SQL statement. This can arise in development if
425 // a change alters the schema but not all queries adjust.
[email protected]eff1fa522011-12-12 23:50:59426 if (error == SQLITE_ERROR)
[email protected]28fe0ff2012-02-25 00:40:33427 DLOG(FATAL) << "SQL Error in " << sql << ", " << GetErrorMessage();
[email protected]eff1fa522011-12-12 23:50:59428 return error == SQLITE_OK;
[email protected]e5ffd0e42009-09-11 21:30:56429}
430
[email protected]5b96f3772010-09-28 16:30:57431bool Connection::ExecuteWithTimeout(const char* sql, base::TimeDelta timeout) {
[email protected]41a97c812013-02-07 02:35:38432 if (!db_) {
433 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]5b96f3772010-09-28 16:30:57434 return false;
[email protected]41a97c812013-02-07 02:35:38435 }
[email protected]5b96f3772010-09-28 16:30:57436
437 ScopedBusyTimeout busy_timeout(db_);
438 busy_timeout.SetTimeout(timeout);
[email protected]eff1fa522011-12-12 23:50:59439 return Execute(sql);
[email protected]5b96f3772010-09-28 16:30:57440}
441
[email protected]e5ffd0e42009-09-11 21:30:56442bool Connection::HasCachedStatement(const StatementID& id) const {
443 return statement_cache_.find(id) != statement_cache_.end();
444}
445
446scoped_refptr<Connection::StatementRef> Connection::GetCachedStatement(
447 const StatementID& id,
448 const char* sql) {
449 CachedStatementMap::iterator i = statement_cache_.find(id);
450 if (i != statement_cache_.end()) {
451 // Statement is in the cache. It should still be active (we're the only
452 // one invalidating cached statements, and we'll remove it from the cache
453 // if we do that. Make sure we reset it before giving out the cached one in
454 // case it still has some stuff bound.
455 DCHECK(i->second->is_valid());
456 sqlite3_reset(i->second->stmt());
457 return i->second;
458 }
459
460 scoped_refptr<StatementRef> statement = GetUniqueStatement(sql);
461 if (statement->is_valid())
462 statement_cache_[id] = statement; // Only cache valid statements.
463 return statement;
464}
465
466scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement(
467 const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50468 AssertIOAllowed();
469
[email protected]41a97c812013-02-07 02:35:38470 // Return inactive statement.
[email protected]e5ffd0e42009-09-11 21:30:56471 if (!db_)
[email protected]41a97c812013-02-07 02:35:38472 return new StatementRef(NULL, NULL, poisoned_);
[email protected]e5ffd0e42009-09-11 21:30:56473
474 sqlite3_stmt* stmt = NULL;
[email protected]473ad792012-11-10 00:55:00475 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
476 if (rc != SQLITE_OK) {
[email protected]eff1fa522011-12-12 23:50:59477 // This is evidence of a syntax error in the incoming SQL.
478 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]473ad792012-11-10 00:55:00479
480 // It could also be database corruption.
481 OnSqliteError(rc, NULL);
[email protected]41a97c812013-02-07 02:35:38482 return new StatementRef(NULL, NULL, false);
[email protected]e5ffd0e42009-09-11 21:30:56483 }
[email protected]41a97c812013-02-07 02:35:38484 return new StatementRef(this, stmt, true);
[email protected]e5ffd0e42009-09-11 21:30:56485}
486
[email protected]2eec0a22012-07-24 01:59:58487scoped_refptr<Connection::StatementRef> Connection::GetUntrackedStatement(
488 const char* sql) const {
[email protected]41a97c812013-02-07 02:35:38489 // Return inactive statement.
[email protected]2eec0a22012-07-24 01:59:58490 if (!db_)
[email protected]41a97c812013-02-07 02:35:38491 return new StatementRef(NULL, NULL, poisoned_);
[email protected]2eec0a22012-07-24 01:59:58492
493 sqlite3_stmt* stmt = NULL;
494 int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
495 if (rc != SQLITE_OK) {
496 // This is evidence of a syntax error in the incoming SQL.
497 DLOG(FATAL) << "SQL compile error " << GetErrorMessage();
[email protected]41a97c812013-02-07 02:35:38498 return new StatementRef(NULL, NULL, false);
[email protected]2eec0a22012-07-24 01:59:58499 }
[email protected]41a97c812013-02-07 02:35:38500 return new StatementRef(NULL, stmt, true);
[email protected]2eec0a22012-07-24 01:59:58501}
502
[email protected]eff1fa522011-12-12 23:50:59503bool Connection::IsSQLValid(const char* sql) {
[email protected]35f7e5392012-07-27 19:54:50504 AssertIOAllowed();
[email protected]41a97c812013-02-07 02:35:38505 if (!db_) {
506 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
507 return false;
508 }
509
[email protected]eff1fa522011-12-12 23:50:59510 sqlite3_stmt* stmt = NULL;
511 if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK)
512 return false;
513
514 sqlite3_finalize(stmt);
515 return true;
516}
517
[email protected]1ed78a32009-09-15 20:24:17518bool Connection::DoesTableExist(const char* table_name) const {
[email protected]e2cadec82011-12-13 02:00:53519 return DoesTableOrIndexExist(table_name, "table");
520}
521
522bool Connection::DoesIndexExist(const char* index_name) const {
523 return DoesTableOrIndexExist(index_name, "index");
524}
525
526bool Connection::DoesTableOrIndexExist(
527 const char* name, const char* type) const {
[email protected]2eec0a22012-07-24 01:59:58528 const char* kSql = "SELECT name FROM sqlite_master WHERE type=? AND name=?";
529 Statement statement(GetUntrackedStatement(kSql));
[email protected]e2cadec82011-12-13 02:00:53530 statement.BindString(0, type);
531 statement.BindString(1, name);
[email protected]28fe0ff2012-02-25 00:40:33532
[email protected]e5ffd0e42009-09-11 21:30:56533 return statement.Step(); // Table exists if any row was returned.
534}
535
536bool Connection::DoesColumnExist(const char* table_name,
[email protected]1ed78a32009-09-15 20:24:17537 const char* column_name) const {
[email protected]e5ffd0e42009-09-11 21:30:56538 std::string sql("PRAGMA TABLE_INFO(");
539 sql.append(table_name);
540 sql.append(")");
541
[email protected]2eec0a22012-07-24 01:59:58542 Statement statement(GetUntrackedStatement(sql.c_str()));
[email protected]e5ffd0e42009-09-11 21:30:56543 while (statement.Step()) {
544 if (!statement.ColumnString(1).compare(column_name))
545 return true;
546 }
547 return false;
548}
549
550int64 Connection::GetLastInsertRowId() const {
551 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38552 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]e5ffd0e42009-09-11 21:30:56553 return 0;
554 }
555 return sqlite3_last_insert_rowid(db_);
556}
557
[email protected]1ed78a32009-09-15 20:24:17558int Connection::GetLastChangeCount() const {
559 if (!db_) {
[email protected]41a97c812013-02-07 02:35:38560 DLOG_IF(FATAL, !poisoned_) << "Illegal use of connection without a db";
[email protected]1ed78a32009-09-15 20:24:17561 return 0;
562 }
563 return sqlite3_changes(db_);
564}
565
[email protected]e5ffd0e42009-09-11 21:30:56566int Connection::GetErrorCode() const {
567 if (!db_)
568 return SQLITE_ERROR;
569 return sqlite3_errcode(db_);
570}
571
[email protected]767718e52010-09-21 23:18:49572int Connection::GetLastErrno() const {
573 if (!db_)
574 return -1;
575
576 int err = 0;
577 if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err))
578 return -2;
579
580 return err;
581}
582
[email protected]e5ffd0e42009-09-11 21:30:56583const char* Connection::GetErrorMessage() const {
584 if (!db_)
585 return "sql::Connection has no connection.";
586 return sqlite3_errmsg(db_);
587}
588
[email protected]765b44502009-10-02 05:01:42589bool Connection::OpenInternal(const std::string& file_name) {
[email protected]35f7e5392012-07-27 19:54:50590 AssertIOAllowed();
591
[email protected]9cfbc922009-11-17 20:13:17592 if (db_) {
[email protected]eff1fa522011-12-12 23:50:59593 DLOG(FATAL) << "sql::Connection is already open.";
[email protected]9cfbc922009-11-17 20:13:17594 return false;
595 }
596
[email protected]41a97c812013-02-07 02:35:38597 // If |poisoned_| is set, it means an error handler called
598 // RazeAndClose(). Until regular Close() is called, the caller
599 // should be treating the database as open, but is_open() currently
600 // only considers the sqlite3 handle's state.
601 // TODO(shess): Revise is_open() to consider poisoned_, and review
602 // to see if any non-testing code even depends on it.
603 DLOG_IF(FATAL, poisoned_) << "sql::Connection is already open.";
604
[email protected]765b44502009-10-02 05:01:42605 int err = sqlite3_open(file_name.c_str(), &db_);
606 if (err != SQLITE_OK) {
[email protected]bd2ccdb4a2012-12-07 22:14:50607 // Histogram failures specific to initial open for debugging
608 // purposes.
609 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenFailure", err & 0xff, 50);
610
[email protected]765b44502009-10-02 05:01:42611 OnSqliteError(err, NULL);
[email protected]64021042012-02-10 20:02:29612 Close();
[email protected]765b44502009-10-02 05:01:42613 db_ = NULL;
614 return false;
615 }
616
[email protected]bd2ccdb4a2012-12-07 22:14:50617 // sqlite3_open() does not actually read the database file (unless a
618 // hot journal is found). Successfully executing this pragma on an
619 // existing database requires a valid header on page 1.
620 // TODO(shess): For now, just probing to see what the lay of the
621 // land is. If it's mostly SQLITE_NOTADB, then the database should
622 // be razed.
623 err = ExecuteAndReturnErrorCode("PRAGMA auto_vacuum");
624 if (err != SQLITE_OK)
625 UMA_HISTOGRAM_ENUMERATION("Sqlite.OpenProbeFailure", err & 0xff, 50);
626
[email protected]658f8332010-09-18 04:40:43627 // Enable extended result codes to provide more color on I/O errors.
628 // Not having extended result codes is not a fatal problem, as
629 // Chromium code does not attempt to handle I/O errors anyhow. The
630 // current implementation always returns SQLITE_OK, the DCHECK is to
631 // quickly notify someone if SQLite changes.
632 err = sqlite3_extended_result_codes(db_, 1);
633 DCHECK_EQ(err, SQLITE_OK) << "Could not enable extended result codes";
634
[email protected]5b96f3772010-09-28 16:30:57635 // If indicated, lock up the database before doing anything else, so
636 // that the following code doesn't have to deal with locking.
637 // TODO(shess): This code is brittle. Find the cases where code
638 // doesn't request |exclusive_locking_| and audit that it does the
639 // right thing with SQLITE_BUSY, and that it doesn't make
640 // assumptions about who might change things in the database.
641 // http://crbug.com/56559
642 if (exclusive_locking_) {
643 // TODO(shess): This should probably be a full CHECK(). Code
644 // which requests exclusive locking but doesn't get it is almost
645 // certain to be ill-tested.
646 if (!Execute("PRAGMA locking_mode=EXCLUSIVE"))
[email protected]eff1fa522011-12-12 23:50:59647 DLOG(FATAL) << "Could not set locking mode: " << GetErrorMessage();
[email protected]5b96f3772010-09-28 16:30:57648 }
649
[email protected]4e179ba2012-03-17 16:06:47650 // http://www.sqlite.org/pragma.html#pragma_journal_mode
651 // DELETE (default) - delete -journal file to commit.
652 // TRUNCATE - truncate -journal file to commit.
653 // PERSIST - zero out header of -journal file to commit.
654 // journal_size_limit provides size to trim to in PERSIST.
655 // TODO(shess): Figure out if PERSIST and journal_size_limit really
656 // matter. In theory, it keeps pages pre-allocated, so if
657 // transactions usually fit, it should be faster.
658 ignore_result(Execute("PRAGMA journal_mode = PERSIST"));
659 ignore_result(Execute("PRAGMA journal_size_limit = 16384"));
660
[email protected]c68ce172011-11-24 22:30:27661 const base::TimeDelta kBusyTimeout =
662 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
663
[email protected]765b44502009-10-02 05:01:42664 if (page_size_ != 0) {
[email protected]5b96f3772010-09-28 16:30:57665 // Enforce SQLite restrictions on |page_size_|.
666 DCHECK(!(page_size_ & (page_size_ - 1)))
667 << " page_size_ " << page_size_ << " is not a power of two.";
[email protected]6d42f152012-11-10 00:38:24668 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
[email protected]5b96f3772010-09-28 16:30:57669 DCHECK_LE(page_size_, kSqliteMaxPageSize);
[email protected]7d3cbc92013-03-18 22:33:04670 const std::string sql =
671 base::StringPrintf("PRAGMA page_size=%d", page_size_);
[email protected]5b96f3772010-09-28 16:30:57672 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59673 DLOG(FATAL) << "Could not set page size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42674 }
675
676 if (cache_size_ != 0) {
[email protected]7d3cbc92013-03-18 22:33:04677 const std::string sql =
678 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
[email protected]5b96f3772010-09-28 16:30:57679 if (!ExecuteWithTimeout(sql.c_str(), kBusyTimeout))
[email protected]eff1fa522011-12-12 23:50:59680 DLOG(FATAL) << "Could not set cache size: " << GetErrorMessage();
[email protected]765b44502009-10-02 05:01:42681 }
682
[email protected]6e0b1442011-08-09 23:23:58683 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
[email protected]eff1fa522011-12-12 23:50:59684 DLOG(FATAL) << "Could not enable secure_delete: " << GetErrorMessage();
[email protected]6e0b1442011-08-09 23:23:58685 Close();
686 return false;
687 }
688
[email protected]765b44502009-10-02 05:01:42689 return true;
690}
691
[email protected]e5ffd0e42009-09-11 21:30:56692void Connection::DoRollback() {
693 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
[email protected]eff1fa522011-12-12 23:50:59694 rollback.Run();
[email protected]44ad7d902012-03-23 00:09:05695 needs_rollback_ = false;
[email protected]e5ffd0e42009-09-11 21:30:56696}
697
698void Connection::StatementRefCreated(StatementRef* ref) {
699 DCHECK(open_statements_.find(ref) == open_statements_.end());
700 open_statements_.insert(ref);
701}
702
703void Connection::StatementRefDeleted(StatementRef* ref) {
704 StatementRefSet::iterator i = open_statements_.find(ref);
705 if (i == open_statements_.end())
[email protected]eff1fa522011-12-12 23:50:59706 DLOG(FATAL) << "Could not find statement";
[email protected]e5ffd0e42009-09-11 21:30:56707 else
708 open_statements_.erase(i);
709}
710
[email protected]faa604e2009-09-25 22:38:59711int Connection::OnSqliteError(int err, sql::Statement *stmt) {
[email protected]c088e3a32013-01-03 23:59:14712 // Strip extended error codes.
713 int base_err = err&0xff;
714
715 static size_t kSqliteErrorMax = 50;
716 UMA_HISTOGRAM_ENUMERATION("Sqlite.Error", base_err, kSqliteErrorMax);
717 if (!error_histogram_name_.empty()) {
718 // TODO(shess): The histogram macros create a bit of static
719 // storage for caching the histogram object. Since SQLite is
720 // being used for I/O, generally without error, this code
721 // shouldn't execute often enough for such caching to be crucial.
722 // If it becomes an issue, the object could be cached alongside
723 // error_histogram_name_.
[email protected]de415552013-01-23 04:12:17724 base::HistogramBase* histogram =
[email protected]c088e3a32013-01-03 23:59:14725 base::LinearHistogram::FactoryGet(
726 error_histogram_name_, 1, kSqliteErrorMax, kSqliteErrorMax + 1,
[email protected]de415552013-01-23 04:12:17727 base::HistogramBase::kUmaTargetedHistogramFlag);
[email protected]c088e3a32013-01-03 23:59:14728 if (histogram)
729 histogram->Add(base_err);
730 }
731
732 // Always log the error.
733 LOG(ERROR) << "sqlite error " << err
734 << ", errno " << GetLastErrno()
735 << ": " << GetErrorMessage();
736
[email protected]faa604e2009-09-25 22:38:59737 if (error_delegate_.get())
738 return error_delegate_->OnError(err, this, stmt);
[email protected]c088e3a32013-01-03 23:59:14739
[email protected]faa604e2009-09-25 22:38:59740 // The default handling is to assert on debug and to ignore on release.
[email protected]eff1fa522011-12-12 23:50:59741 DLOG(FATAL) << GetErrorMessage();
[email protected]faa604e2009-09-25 22:38:59742 return err;
743}
744
[email protected]e5ffd0e42009-09-11 21:30:56745} // namespace sql