diff options
author | brettw@chromium.org <brettw@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2009-09-15 20:24:17 +0000 |
---|---|---|
committer | brettw@chromium.org <brettw@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2009-09-15 20:24:17 +0000 |
commit | 1ed78a31b405c4b85a3747d697e464508e7c4399 (patch) | |
tree | f76654969406d9bfe3d8a5ca70f4fcb76f5199f8 | |
parent | 2627431bef905332e55a90960aed8049b681689f (diff) | |
download | chromium_src-1ed78a31b405c4b85a3747d697e464508e7c4399.zip chromium_src-1ed78a31b405c4b85a3747d697e464508e7c4399.tar.gz chromium_src-1ed78a31b405c4b85a3747d697e464508e7c4399.tar.bz2 |
Convert the sqlite cookie database and web database to use the new sqlite
wrapper. This also moves and renamed the old cookie_monster_sqlite file to
match the class name.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/201099
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@26260 0039d316-1c4b-4281-b951-d872f2087c98
-rw-r--r-- | app/sql/connection.cc | 20 | ||||
-rw-r--r-- | app/sql/connection.h | 9 | ||||
-rw-r--r-- | app/sql/statement.cc | 12 | ||||
-rw-r--r-- | app/sql/statement.h | 7 | ||||
-rw-r--r-- | chrome/browser/net/chrome_url_request_context.cc | 7 | ||||
-rw-r--r-- | chrome/browser/net/chrome_url_request_context.h | 3 | ||||
-rw-r--r-- | chrome/browser/net/sqlite_persistent_cookie_store.cc (renamed from chrome/common/net/cookie_monster_sqlite.cc) | 203 | ||||
-rw-r--r-- | chrome/browser/net/sqlite_persistent_cookie_store.h (renamed from chrome/common/net/cookie_monster_sqlite.h) | 23 | ||||
-rw-r--r-- | chrome/browser/profile.cc | 1 | ||||
-rw-r--r-- | chrome/browser/webdata/web_data_service.cc | 3 | ||||
-rw-r--r-- | chrome/browser/webdata/web_database.cc | 889 | ||||
-rw-r--r-- | chrome/browser/webdata/web_database.h | 50 | ||||
-rw-r--r-- | chrome/browser/webdata/web_database_unittest.cc | 22 | ||||
-rw-r--r-- | chrome/browser/webdata/web_database_win.cc | 63 | ||||
-rw-r--r-- | chrome/chrome.gyp | 4 |
15 files changed, 630 insertions, 686 deletions
diff --git a/app/sql/connection.cc b/app/sql/connection.cc index 4878e1b..53ab07d 100644 --- a/app/sql/connection.cc +++ b/app/sql/connection.cc @@ -224,8 +224,10 @@ scoped_refptr<Connection::StatementRef> Connection::GetUniqueStatement( return new StatementRef(this, stmt); } -bool Connection::DoesTableExist(const char* table_name) { - Statement statement(GetUniqueStatement( +bool Connection::DoesTableExist(const char* table_name) const { + // GetUniqueStatement can't be const since statements may modify the + // database, but we know ours doesn't modify it, so the cast is safe. + Statement statement(const_cast<Connection*>(this)->GetUniqueStatement( "SELECT name FROM sqlite_master " "WHERE type='table' AND name=?")); if (!statement) @@ -235,12 +237,14 @@ bool Connection::DoesTableExist(const char* table_name) { } bool Connection::DoesColumnExist(const char* table_name, - const char* column_name) { + const char* column_name) const { std::string sql("PRAGMA TABLE_INFO("); sql.append(table_name); sql.append(")"); - Statement statement(GetUniqueStatement(sql.c_str())); + // Our SQL is non-mutating, so this cast is OK. + Statement statement(const_cast<Connection*>(this)->GetUniqueStatement( + sql.c_str())); if (!statement) return false; @@ -259,6 +263,14 @@ int64 Connection::GetLastInsertRowId() const { return sqlite3_last_insert_rowid(db_); } +int Connection::GetLastChangeCount() const { + if (!db_) { + NOTREACHED(); + return 0; + } + return sqlite3_changes(db_); +} + int Connection::GetErrorCode() const { if (!db_) return SQLITE_ERROR; diff --git a/app/sql/connection.h b/app/sql/connection.h index 2bb450a..cd9d213 100644 --- a/app/sql/connection.h +++ b/app/sql/connection.h @@ -197,15 +197,20 @@ class Connection { // Info querying ------------------------------------------------------------- // Returns true if the given table exists. - bool DoesTableExist( const char* table_name); + bool DoesTableExist( const char* table_name) const; // Returns true if a column with the given name exists in the given table. - bool DoesColumnExist(const char* table_name, const char* column_name); + bool DoesColumnExist(const char* table_name, const char* column_name) const; // Returns sqlite's internal ID for the last inserted row. Valid only // immediately after an insert. int64 GetLastInsertRowId() const; + // Returns sqlite's count of the number of rows modified by the last + // statement executed. Will be 0 if no statement has executed or the database + // is closed. + int GetLastChangeCount() const; + // Errors -------------------------------------------------------------------- // Returns the error code associated with the last sqlite operation. diff --git a/app/sql/statement.cc b/app/sql/statement.cc index 0b419ba..f625e86 100644 --- a/app/sql/statement.cc +++ b/app/sql/statement.cc @@ -170,7 +170,7 @@ std::string Statement::ColumnString(int col) const { return result; } -int Statement::ColumnByteLength(int col) { +int Statement::ColumnByteLength(int col) const { if (!is_valid()) { NOTREACHED(); return 0; @@ -178,7 +178,7 @@ int Statement::ColumnByteLength(int col) { return sqlite3_column_bytes(ref_->stmt(), col); } -const void* Statement::ColumnBlob(int col) { +const void* Statement::ColumnBlob(int col) const { if (!is_valid()) { NOTREACHED(); return NULL; @@ -187,7 +187,7 @@ const void* Statement::ColumnBlob(int col) { return sqlite3_column_blob(ref_->stmt(), col); } -void Statement::ColumnBlobAsVector(int col, std::vector<char>* val) { +void Statement::ColumnBlobAsVector(int col, std::vector<char>* val) const { val->clear(); if (!is_valid()) { NOTREACHED(); @@ -202,6 +202,12 @@ void Statement::ColumnBlobAsVector(int col, std::vector<char>* val) { } } +void Statement::ColumnBlobAsVector( + int col, + std::vector<unsigned char>* val) const { + ColumnBlobAsVector(col, reinterpret_cast< std::vector<char>* >(val)); +} + int Statement::CheckError(int err) { succeeded_ = (err == SQLITE_OK || err == SQLITE_ROW || err == SQLITE_DONE); diff --git a/app/sql/statement.h b/app/sql/statement.h index 371bc4e..a711ae5 100644 --- a/app/sql/statement.h +++ b/app/sql/statement.h @@ -105,9 +105,10 @@ class Statement { // When reading a blob, you can get a raw pointer to the underlying data, // along with the length, or you can just ask us to copy the blob into a // vector. Danger! ColumnBlob may return NULL if there is no data! - int ColumnByteLength(int col); - const void* ColumnBlob(int col); - void ColumnBlobAsVector(int col, std::vector<char>* val); + int ColumnByteLength(int col) const; + const void* ColumnBlob(int col) const; + void ColumnBlobAsVector(int col, std::vector<char>* val) const; + void ColumnBlobAsVector(int col, std::vector<unsigned char>* val) const; private: // This is intended to check for serious errors and report them to the diff --git a/chrome/browser/net/chrome_url_request_context.cc b/chrome/browser/net/chrome_url_request_context.cc index 4683e61..27d8e82 100644 --- a/chrome/browser/net/chrome_url_request_context.cc +++ b/chrome/browser/net/chrome_url_request_context.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -11,6 +11,7 @@ #include "chrome/browser/chrome_thread.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" +#include "chrome/browser/net/sqlite_persistent_cookie_store.h" #include "chrome/browser/net/dns_global.h" #include "chrome/browser/profile.h" #include "chrome/common/chrome_constants.h" @@ -158,7 +159,7 @@ ChromeURLRequestContext* ChromeURLRequestContext::CreateOriginal( scoped_refptr<SQLitePersistentCookieStore> cookie_db = new SQLitePersistentCookieStore( - cookie_store_path.ToWStringHack(), + cookie_store_path, g_browser_process->db_thread()->message_loop()); context->cookie_store_ = new net::CookieMonster(cookie_db.get()); } @@ -185,7 +186,7 @@ ChromeURLRequestContext* ChromeURLRequestContext::CreateOriginalForExtensions( scoped_refptr<SQLitePersistentCookieStore> cookie_db = new SQLitePersistentCookieStore( - cookie_store_path.ToWStringHack(), + cookie_store_path, g_browser_process->db_thread()->message_loop()); net::CookieMonster* cookie_monster = new net::CookieMonster(cookie_db.get()); diff --git a/chrome/browser/net/chrome_url_request_context.h b/chrome/browser/net/chrome_url_request_context.h index 067cf10a..b78e0a7 100644 --- a/chrome/browser/net/chrome_url_request_context.h +++ b/chrome/browser/net/chrome_url_request_context.h @@ -1,10 +1,9 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "chrome/common/appcache/chrome_appcache_service.h" -#include "chrome/common/net/cookie_monster_sqlite.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/pref_service.h" #include "net/url_request/url_request_context.h" diff --git a/chrome/common/net/cookie_monster_sqlite.cc b/chrome/browser/net/sqlite_persistent_cookie_store.cc index a292463..ce371f5 100644 --- a/chrome/common/net/cookie_monster_sqlite.cc +++ b/chrome/browser/net/sqlite_persistent_cookie_store.cc @@ -1,18 +1,19 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/common/net/cookie_monster_sqlite.h" +#include "chrome/browser/net/sqlite_persistent_cookie_store.h" #include <list> +#include "app/sql/statement.h" +#include "app/sql/transaction.h" #include "base/basictypes.h" #include "base/logging.h" #include "base/ref_counted.h" +#include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/thread.h" -#include "chrome/common/sqlite_compiled_statement.h" -#include "chrome/common/sqlite_utils.h" using base::Time; @@ -23,10 +24,9 @@ class SQLitePersistentCookieStore::Backend public: // The passed database pointer must be already-initialized. This object will // take ownership. - explicit Backend(sqlite3* db, MessageLoop* loop) + explicit Backend(sql::Connection* db, MessageLoop* loop) : db_(db), background_loop_(loop), - cache_(new SqliteStatementCache(db)), num_pending_(0) { DCHECK(db_) << "Database must exist."; } @@ -85,9 +85,8 @@ class SQLitePersistentCookieStore::Backend // Close() executed on the background thread. void InternalBackgroundClose(); - sqlite3* db_; + sql::Connection* db_; MessageLoop* background_loop_; - SqliteStatementCache* cache_; typedef std::list<PendingOperation*> PendingOperationsList; PendingOperationsList pending_; @@ -159,70 +158,69 @@ void SQLitePersistentCookieStore::Backend::Commit() { if (!db_ || ops.empty()) return; - SQLITE_UNIQUE_STATEMENT(add_smt, *cache_, + sql::Statement add_smt(db_->GetCachedStatement(SQL_FROM_HERE, "INSERT INTO cookies (creation_utc, host_key, name, value, path, " "expires_utc, secure, httponly, last_access_utc) " - "VALUES (?,?,?,?,?,?,?,?,?)"); - if (!add_smt.is_valid()) { + "VALUES (?,?,?,?,?,?,?,?,?)")); + if (!add_smt) { NOTREACHED(); return; } - SQLITE_UNIQUE_STATEMENT(update_access_smt, *cache_, - "UPDATE cookies SET last_access_utc=? " - "WHERE creation_utc=?"); - if (!update_access_smt.is_valid()) { + sql::Statement update_access_smt(db_->GetCachedStatement(SQL_FROM_HERE, + "UPDATE cookies SET last_access_utc=? WHERE creation_utc=?")); + if (!update_access_smt) { NOTREACHED(); return; } - SQLITE_UNIQUE_STATEMENT(del_smt, *cache_, - "DELETE FROM cookies WHERE creation_utc=?"); - if (!del_smt.is_valid()) { + sql::Statement del_smt(db_->GetCachedStatement(SQL_FROM_HERE, + "DELETE FROM cookies WHERE creation_utc=?")); + if (!del_smt) { NOTREACHED(); return; } - SQLTransaction transaction(db_); - transaction.Begin(); + sql::Transaction transaction(db_); + if (!transaction.Begin()) { + NOTREACHED(); + return; + } for (PendingOperationsList::iterator it = ops.begin(); it != ops.end(); ++it) { // Free the cookies as we commit them to the database. scoped_ptr<PendingOperation> po(*it); switch (po->op()) { case PendingOperation::COOKIE_ADD: - add_smt->reset(); - add_smt->bind_int64(0, po->cc().CreationDate().ToInternalValue()); - add_smt->bind_string(1, po->key()); - add_smt->bind_string(2, po->cc().Name()); - add_smt->bind_string(3, po->cc().Value()); - add_smt->bind_string(4, po->cc().Path()); - add_smt->bind_int64(5, po->cc().ExpiryDate().ToInternalValue()); - add_smt->bind_int(6, po->cc().IsSecure()); - add_smt->bind_int(7, po->cc().IsHttpOnly()); - add_smt->bind_int64(8, po->cc().LastAccessDate().ToInternalValue()); - if (add_smt->step() != SQLITE_DONE) { + add_smt.Reset(); + add_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue()); + add_smt.BindString(1, po->key()); + add_smt.BindString(2, po->cc().Name()); + add_smt.BindString(3, po->cc().Value()); + add_smt.BindString(4, po->cc().Path()); + add_smt.BindInt64(5, po->cc().ExpiryDate().ToInternalValue()); + add_smt.BindInt(6, po->cc().IsSecure()); + add_smt.BindInt(7, po->cc().IsHttpOnly()); + add_smt.BindInt64(8, po->cc().LastAccessDate().ToInternalValue()); + if (!add_smt.Run()) NOTREACHED() << "Could not add a cookie to the DB."; - } break; case PendingOperation::COOKIE_UPDATEACCESS: - update_access_smt->reset(); - update_access_smt->bind_int64(0, + update_access_smt.Reset(); + update_access_smt.BindInt64(0, po->cc().LastAccessDate().ToInternalValue()); - update_access_smt->bind_int64(1, + update_access_smt.BindInt64(1, po->cc().CreationDate().ToInternalValue()); - if (update_access_smt->step() != SQLITE_DONE) { + if (!update_access_smt.Run()) NOTREACHED() << "Could not update cookie last access time in the DB."; - } break; case PendingOperation::COOKIE_DELETE: - del_smt->reset(); - del_smt->bind_int64(0, po->cc().CreationDate().ToInternalValue()); - if (del_smt->step() != SQLITE_DONE) { + del_smt.Reset(); + del_smt.BindInt64(0, po->cc().CreationDate().ToInternalValue()); + if (!del_smt.Run()) NOTREACHED() << "Could not delete a cookie from the DB."; - } break; default: @@ -248,15 +246,14 @@ void SQLitePersistentCookieStore::Backend::InternalBackgroundClose() { DCHECK(MessageLoop::current() == background_loop_); // Commit any pending operations Commit(); - // We must destroy the cache before closing the database. - delete cache_; - cache_ = NULL; - sqlite3_close(db_); + + delete db_; db_ = NULL; } SQLitePersistentCookieStore::SQLitePersistentCookieStore( - const std::wstring& path, MessageLoop* background_loop) + const FilePath& path, + MessageLoop* background_loop) : path_(path), background_loop_(background_loop) { DCHECK(background_loop) << "SQLitePersistentCookieStore needs a MessageLoop"; @@ -285,28 +282,25 @@ static const int kCompatibleVersionNumber = 3; namespace { // Initializes the cookies table, returning true on success. -bool InitTable(sqlite3* db) { - if (!DoesSqliteTableExist(db, "cookies")) { - if (sqlite3_exec(db, "CREATE TABLE cookies (" - "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY," - "host_key TEXT NOT NULL," - "name TEXT NOT NULL," - "value TEXT NOT NULL," - "path TEXT NOT NULL," - // We only store persistent, so we know it expires - "expires_utc INTEGER NOT NULL," - "secure INTEGER NOT NULL," - "httponly INTEGER NOT NULL," - "last_access_utc INTEGER NOT NULL)", - NULL, NULL, NULL) != SQLITE_OK) +bool InitTable(sql::Connection* db) { + if (!db->DoesTableExist("cookies")) { + if (!db->Execute("CREATE TABLE cookies (" + "creation_utc INTEGER NOT NULL UNIQUE PRIMARY KEY," + "host_key TEXT NOT NULL," + "name TEXT NOT NULL," + "value TEXT NOT NULL," + "path TEXT NOT NULL," + // We only store persistent, so we know it expires + "expires_utc INTEGER NOT NULL," + "secure INTEGER NOT NULL," + "httponly INTEGER NOT NULL," + "last_access_utc INTEGER NOT NULL)")) return false; } // Try to create the index every time. Older versions did not have this index, // so we want those people to get it. Ignore errors, since it may exist. - sqlite3_exec(db, "CREATE INDEX cookie_times ON cookies (creation_utc)", - NULL, NULL, NULL); - + db->Execute("CREATE INDEX cookie_times ON cookies (creation_utc)"); return true; } @@ -314,65 +308,55 @@ bool InitTable(sqlite3* db) { bool SQLitePersistentCookieStore::Load( std::vector<net::CookieMonster::KeyedCanonicalCookie>* cookies) { - DCHECK(!path_.empty()); - sqlite3* db; - if (sqlite3_open(WideToUTF8(path_).c_str(), &db) != SQLITE_OK) { + scoped_ptr<sql::Connection> db(new sql::Connection); + if (!db->Init(path_)) { NOTREACHED() << "Unable to open cookie DB."; return false; } - if (!EnsureDatabaseVersion(db) || !InitTable(db)) { + if (!EnsureDatabaseVersion(db.get()) || !InitTable(db.get())) { NOTREACHED() << "Unable to initialize cookie DB."; - sqlite3_close(db); return false; } - MetaTableHelper::PrimeCache(std::string(), db); + db->Preload(); // Slurp all the cookies into the out-vector. - SQLStatement smt; - if (smt.prepare(db, + sql::Statement smt(db->GetUniqueStatement( "SELECT creation_utc, host_key, name, value, path, expires_utc, secure, " - "httponly, last_access_utc FROM cookies") != SQLITE_OK) { + "httponly, last_access_utc FROM cookies")); + if (!smt) { NOTREACHED() << "select statement prep failed"; - sqlite3_close(db); return false; } - while (smt.step() == SQLITE_ROW) { - std::string key = smt.column_string(1); + while (smt.Step()) { scoped_ptr<net::CookieMonster::CanonicalCookie> cc( new net::CookieMonster::CanonicalCookie( - smt.column_string(2), // name - smt.column_string(3), // value - smt.column_string(4), // path - smt.column_int(6) != 0, // secure - smt.column_int(7) != 0, // httponly - Time::FromInternalValue(smt.column_int64(0)), // creation_utc - Time::FromInternalValue(smt.column_int64(8)), // last_access_utc - true, // has_expires - Time::FromInternalValue(smt.column_int64(5)))); // expires_utc - // Memory allocation failed. - if (!cc.get()) - break; - + smt.ColumnString(2), // name + smt.ColumnString(3), // value + smt.ColumnString(4), // path + smt.ColumnInt(6) != 0, // secure + smt.ColumnInt(7) != 0, // httponly + Time::FromInternalValue(smt.ColumnInt64(0)), // creation_utc + Time::FromInternalValue(smt.ColumnInt64(8)), // last_access_utc + true, // has_expires + Time::FromInternalValue(smt.ColumnInt64(5)))); // expires_utc DLOG_IF(WARNING, cc->CreationDate() > Time::Now()) << L"CreationDate too recent"; cookies->push_back( - net::CookieMonster::KeyedCanonicalCookie(smt.column_string(1), + net::CookieMonster::KeyedCanonicalCookie(smt.ColumnString(1), cc.release())); } // Create the backend, this will take ownership of the db pointer. - backend_ = new Backend(db, background_loop_); - + backend_ = new Backend(db.release(), background_loop_); return true; } -bool SQLitePersistentCookieStore::EnsureDatabaseVersion(sqlite3* db) { +bool SQLitePersistentCookieStore::EnsureDatabaseVersion(sql::Connection* db) { // Version check. - if (!meta_table_.Init(std::string(), kCurrentVersionNumber, - kCompatibleVersionNumber, db)) + if (!meta_table_.Init(db, kCurrentVersionNumber, kCompatibleVersionNumber)) return false; if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) { @@ -382,14 +366,12 @@ bool SQLitePersistentCookieStore::EnsureDatabaseVersion(sqlite3* db) { int cur_version = meta_table_.GetVersionNumber(); if (cur_version == 2) { - SQLTransaction transaction(db); - transaction.Begin(); - if ((sqlite3_exec(db, - "ALTER TABLE cookies ADD COLUMN last_access_utc " - "INTEGER DEFAULT 0", NULL, NULL, NULL) != SQLITE_OK) || - (sqlite3_exec(db, - "UPDATE cookies SET last_access_utc = creation_utc", - NULL, NULL, NULL) != SQLITE_OK)) { + sql::Transaction transaction(db); + if (!transaction.Begin()) + return false; + if (!db->Execute("ALTER TABLE cookies ADD COLUMN last_access_utc " + "INTEGER DEFAULT 0") || + !db->Execute("UPDATE cookies SET last_access_utc = creation_utc")) { LOG(WARNING) << "Unable to update cookie database to version 3."; return false; } @@ -407,30 +389,27 @@ bool SQLitePersistentCookieStore::EnsureDatabaseVersion(sqlite3* db) { // versions. So we have to be careful to only update times that are under // the old system (which will appear to be from before 1970 in the new // system). The magic number used below is 1970 in our time units. - SQLTransaction transaction(db); + sql::Transaction transaction(db); transaction.Begin(); #if !defined(OS_WIN) - sqlite3_exec(db, + db->Execute( "UPDATE cookies " "SET creation_utc = creation_utc + 11644473600000000 " "WHERE rowid IN " "(SELECT rowid FROM cookies WHERE " - "creation_utc > 0 AND creation_utc < 11644473600000000)", - NULL, NULL, NULL); - sqlite3_exec(db, + "creation_utc > 0 AND creation_utc < 11644473600000000)"); + db->Execute( "UPDATE cookies " "SET expires_utc = expires_utc + 11644473600000000 " "WHERE rowid IN " "(SELECT rowid FROM cookies WHERE " - "expires_utc > 0 AND expires_utc < 11644473600000000)", - NULL, NULL, NULL); - sqlite3_exec(db, + "expires_utc > 0 AND expires_utc < 11644473600000000)"); + db->Execute( "UPDATE cookies " "SET last_access_utc = last_access_utc + 11644473600000000 " "WHERE rowid IN " "(SELECT rowid FROM cookies WHERE " - "last_access_utc > 0 AND last_access_utc < 11644473600000000)", - NULL, NULL, NULL); + "last_access_utc > 0 AND last_access_utc < 11644473600000000)"); #endif ++cur_version; meta_table_.SetVersionNumber(cur_version); diff --git a/chrome/common/net/cookie_monster_sqlite.h b/chrome/browser/net/sqlite_persistent_cookie_store.h index a4774eb..fe7e3f0 100644 --- a/chrome/common/net/cookie_monster_sqlite.h +++ b/chrome/browser/net/sqlite_persistent_cookie_store.h @@ -1,27 +1,28 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // A sqlite implementation of a cookie monster persistent store. -#ifndef CHROME_COMMON_NET_COOKIE_MONSTER_SQLITE_H__ -#define CHROME_COMMON_NET_COOKIE_MONSTER_SQLITE_H__ +#ifndef CHROME_BROWSER_NET_SQLITE_PERSISTENT_COOKIE_STORE_H_ +#define CHROME_BROWSER_NET_SQLITE_PERSISTENT_COOKIE_STORE_H_ #include <string> #include <vector> +#include "app/sql/connection.h" +#include "app/sql/meta_table.h" +#include "base/file_path.h" #include "base/ref_counted.h" -#include "chrome/browser/meta_table_helper.h" #include "net/base/cookie_monster.h" -struct sqlite3; - +class FilePath; class MessageLoop; class SQLitePersistentCookieStore : public net::CookieMonster::PersistentCookieStore { public: - SQLitePersistentCookieStore(const std::wstring& path, + SQLitePersistentCookieStore(const FilePath& path, MessageLoop* background_loop); ~SQLitePersistentCookieStore(); @@ -37,17 +38,17 @@ class SQLitePersistentCookieStore class Backend; // Database upgrade statements. - bool EnsureDatabaseVersion(sqlite3* db); + bool EnsureDatabaseVersion(sql::Connection* db); - std::wstring path_; + FilePath path_; scoped_refptr<Backend> backend_; // Background MessageLoop on which to access the backend_; MessageLoop* background_loop_; - MetaTableHelper meta_table_; + sql::MetaTable meta_table_; DISALLOW_COPY_AND_ASSIGN(SQLitePersistentCookieStore); }; -#endif // CHROME_COMMON_NET_COOKIE_MONSTER_SQLITE_H__ +#endif // CHROME_BROWSER_NET_SQLITE_PERSISTENT_COOKIE_STORE_H_ diff --git a/chrome/browser/profile.cc b/chrome/browser/profile.cc index 85b809b..10cb6a1 100644 --- a/chrome/browser/profile.cc +++ b/chrome/browser/profile.cc @@ -45,7 +45,6 @@ #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension_error_reporter.h" -#include "chrome/common/net/cookie_monster_sqlite.h" #include "chrome/common/notification_service.h" #include "chrome/common/pref_names.h" #include "chrome/common/render_messages.h" diff --git a/chrome/browser/webdata/web_data_service.cc b/chrome/browser/webdata/web_data_service.cc index c428729..d7f3682 100644 --- a/chrome/browser/webdata/web_data_service.cc +++ b/chrome/browser/webdata/web_data_service.cc @@ -408,14 +408,13 @@ void WebDataService::InitializeDatabase(const FilePath& path) { // we only set db_ to the created database if creation is successful. That // way other methods won't do anything as db_ is still NULL. WebDatabase* db = new WebDatabase(); - if (!db->Init(path.ToWStringHack())) { + if (!db->Init(path)) { NOTREACHED() << "Cannot initialize the web database"; delete db; return; } db_ = db; - db_->BeginTransaction(); } diff --git a/chrome/browser/webdata/web_database.cc b/chrome/browser/webdata/web_database.cc index 77e41bc..a704173 100644 --- a/chrome/browser/webdata/web_database.cc +++ b/chrome/browser/webdata/web_database.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -9,6 +9,8 @@ #include <vector> #include "app/l10n_util.h" +#include "app/sql/statement.h" +#include "app/sql/transaction.h" #include "base/gfx/png_decoder.h" #include "base/gfx/png_encoder.h" #include "base/string_util.h" @@ -117,65 +119,44 @@ std::string JoinStrings(const std::string& separator, return result; } -WebDatabase::WebDatabase() : db_(NULL), transaction_nesting_(0) { +WebDatabase::WebDatabase() { } WebDatabase::~WebDatabase() { - if (db_) { - DCHECK(transaction_nesting_ == 0) << - "Forgot to close the transaction on shutdown"; - sqlite3_close(db_); - db_ = NULL; - } } void WebDatabase::BeginTransaction() { - DCHECK(db_); - if (transaction_nesting_ == 0) { - int rv = sqlite3_exec(db_, "BEGIN TRANSACTION", NULL, NULL, NULL); - DCHECK(rv == SQLITE_OK) << "Failed to begin transaction"; - } - transaction_nesting_++; + db_.BeginTransaction(); } void WebDatabase::CommitTransaction() { - DCHECK(db_); - DCHECK(transaction_nesting_ > 0) << "Committing too many transaction"; - transaction_nesting_--; - if (transaction_nesting_ == 0) { - int rv = sqlite3_exec(db_, "COMMIT", NULL, NULL, NULL); - DCHECK(rv == SQLITE_OK) << "Failed to commit transaction"; - } + db_.CommitTransaction(); } -bool WebDatabase::Init(const std::wstring& db_name) { - // Open the database, using the narrow version of open so that - // the DB is in UTF-8. - if (sqlite3_open(WideToUTF8(db_name).c_str(), &db_) != SQLITE_OK) { - LOG(WARNING) << "Unable to open the web database."; - return false; - } - +bool WebDatabase::Init(const FilePath& db_name) { // We don't store that much data in the tables so use a small page size. // This provides a large benefit for empty tables (which is very likely with // the tables we create). - sqlite3_exec(db_, "PRAGMA page_size=2048", NULL, NULL, NULL); + db_.set_page_size(2048); // We shouldn't have much data and what access we currently have is quite // infrequent. So we go with a small cache size. - sqlite3_exec(db_, "PRAGMA cache_size=32", NULL, NULL, NULL); + db_.set_cache_size(32); // Run the database in exclusive mode. Nobody else should be accessing the // database while we're running, and this will give somewhat improved perf. - sqlite3_exec(db_, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL, NULL); + db_.set_exclusive_locking(); + + if (!db_.Init(db_name)) + return false; // Initialize various tables - SQLTransaction transaction(db_); - transaction.Begin(); + sql::Transaction transaction(&db_); + if (!transaction.Begin()) + return false; // Version check. - if (!meta_table_.Init(std::string(), kCurrentVersionNumber, - kCompatibleVersionNumber, db_)) + if (!meta_table_.Init(&db_, kCurrentVersionNumber, kCompatibleVersionNumber)) return false; if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) { LOG(WARNING) << "Web database is too new."; @@ -193,48 +174,50 @@ bool WebDatabase::Init(const std::wstring& db_name) { // If the file on disk is an older database version, bring it up to date. MigrateOldVersionsAsNeeded(); - return (transaction.Commit() == SQLITE_OK); + return transaction.Commit(); } -bool WebDatabase::SetWebAppImage(const GURL& url, - const SkBitmap& image) { - SQLStatement s; - if (s.prepare(db_, - "INSERT OR REPLACE INTO web_app_icons " - "(url, width, height, image) VALUES (?, ?, ?, ?)") - != SQLITE_OK) { - NOTREACHED() << "Statement prepare failed"; +bool WebDatabase::SetWebAppImage(const GURL& url, const SkBitmap& image) { + // Don't bother with a cached statement since this will be a relatively + // infrequent operation. + sql::Statement s(db_.GetUniqueStatement( + "INSERT OR REPLACE INTO web_app_icons " + "(url, width, height, image) VALUES (?, ?, ?, ?)")); + if (!s) return false; - } std::vector<unsigned char> image_data; PNGEncoder::EncodeBGRASkBitmap(image, false, &image_data); - s.bind_string(0, history::HistoryDatabase::GURLToDatabaseURL(url)); - s.bind_int(1, image.width()); - s.bind_int(2, image.height()); - s.bind_blob(3, &image_data.front(), static_cast<int>(image_data.size())); - return s.step() == SQLITE_DONE; + s.BindString(0, history::HistoryDatabase::GURLToDatabaseURL(url)); + s.BindInt(1, image.width()); + s.BindInt(2, image.height()); + s.BindBlob(3, &image_data.front(), static_cast<int>(image_data.size())); + return s.Run(); } bool WebDatabase::GetWebAppImages(const GURL& url, - std::vector<SkBitmap>* images) const { - SQLStatement s; - if (s.prepare(db_, "SELECT image FROM web_app_icons WHERE url=?") != - SQLITE_OK) { + std::vector<SkBitmap>* images) { + sql::Statement s(db_.GetUniqueStatement( + "SELECT image FROM web_app_icons WHERE url=?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_string(0, history::HistoryDatabase::GURLToDatabaseURL(url)); - while (s.step() == SQLITE_ROW) { + s.BindString(0, history::HistoryDatabase::GURLToDatabaseURL(url)); + while (s.Step()) { SkBitmap image; std::vector<unsigned char> image_data; - s.column_blob_as_vector(0, &image_data); - if (PNGDecoder::Decode(&image_data, &image)) { - images->push_back(image); - } else { - // Should only have valid image data in the db. - NOTREACHED(); + int col_bytes = s.ColumnByteLength(0); + if (col_bytes > 0) { + image_data.resize(col_bytes); + memcpy(&image_data[0], s.ColumnBlob(0), col_bytes); + if (PNGDecoder::Decode(&image_data, &image)) { + images->push_back(image); + } else { + // Should only have valid image data in the db. + NOTREACHED(); + } } } return true; @@ -242,52 +225,52 @@ bool WebDatabase::GetWebAppImages(const GURL& url, bool WebDatabase::SetWebAppHasAllImages(const GURL& url, bool has_all_images) { - SQLStatement s; - if (s.prepare(db_, "INSERT OR REPLACE INTO web_apps (url, has_all_images) " - "VALUES (?, ?)") != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement( + "INSERT OR REPLACE INTO web_apps (url, has_all_images) VALUES (?, ?)")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_string(0, history::HistoryDatabase::GURLToDatabaseURL(url)); - s.bind_int(1, has_all_images ? 1 : 0); - return (s.step() == SQLITE_DONE); + s.BindString(0, history::HistoryDatabase::GURLToDatabaseURL(url)); + s.BindInt(1, has_all_images ? 1 : 0); + return s.Run(); } -bool WebDatabase::GetWebAppHasAllImages(const GURL& url) const { - SQLStatement s; - if (s.prepare(db_, "SELECT has_all_images FROM web_apps " - "WHERE url=?") != SQLITE_OK) { +bool WebDatabase::GetWebAppHasAllImages(const GURL& url) { + sql::Statement s(db_.GetUniqueStatement( + "SELECT has_all_images FROM web_apps WHERE url=?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_string(0, history::HistoryDatabase::GURLToDatabaseURL(url)); - return (s.step() == SQLITE_ROW && s.column_int(0) == 1); + s.BindString(0, history::HistoryDatabase::GURLToDatabaseURL(url)); + return (s.Step() && s.ColumnInt(0) == 1); } bool WebDatabase::RemoveWebApp(const GURL& url) { - SQLStatement delete_s; - if (delete_s.prepare(db_, "DELETE FROM web_app_icons WHERE url = ?") != - SQLITE_OK) { + sql::Statement delete_s(db_.GetUniqueStatement( + "DELETE FROM web_app_icons WHERE url = ?")); + if (!delete_s) { NOTREACHED() << "Statement prepare failed"; return false; } - delete_s.bind_string(0, history::HistoryDatabase::GURLToDatabaseURL(url)); - if (delete_s.step() != SQLITE_DONE) + delete_s.BindString(0, history::HistoryDatabase::GURLToDatabaseURL(url)); + if (!delete_s.Run()) return false; - SQLStatement delete_s2; - if (delete_s2.prepare(db_, "DELETE FROM web_apps WHERE url = ?") != - SQLITE_OK) { + sql::Statement delete_s2(db_.GetUniqueStatement( + "DELETE FROM web_apps WHERE url = ?")); + if (!delete_s2) { NOTREACHED() << "Statement prepare failed"; return false; } - delete_s2.bind_string(0, history::HistoryDatabase::GURLToDatabaseURL(url)); - return (delete_s2.step() == SQLITE_DONE); + delete_s2.BindString(0, history::HistoryDatabase::GURLToDatabaseURL(url)); + return delete_s2.Run(); } bool WebDatabase::InitKeywordsTable() { - if (!DoesSqliteTableExist(db_, "keywords")) { - if (sqlite3_exec(db_, "CREATE TABLE keywords (" + if (!db_.DoesTableExist("keywords")) { + if (!db_.Execute("CREATE TABLE keywords (" "id INTEGER PRIMARY KEY," "short_name VARCHAR NOT NULL," "keyword VARCHAR NOT NULL," @@ -301,8 +284,7 @@ bool WebDatabase::InitKeywordsTable() { "input_encodings VARCHAR," "suggest_url VARCHAR," "prepopulate_id INTEGER DEFAULT 0," - "autogenerate_keyword INTEGER DEFAULT 0)", - NULL, NULL, NULL) != SQLITE_OK) { + "autogenerate_keyword INTEGER DEFAULT 0)")) { NOTREACHED(); return false; } @@ -311,9 +293,8 @@ bool WebDatabase::InitKeywordsTable() { } bool WebDatabase::InitLoginsTable() { - if (!DoesSqliteTableExist(db_, "logins")) { - // First time - if (sqlite3_exec(db_, "CREATE TABLE logins (" + if (!db_.DoesTableExist("logins")) { + if (!db_.Execute("CREATE TABLE logins (" "origin_url VARCHAR NOT NULL, " "action_url VARCHAR, " "username_element VARCHAR, " @@ -330,35 +311,29 @@ bool WebDatabase::InitLoginsTable() { "UNIQUE " "(origin_url, username_element, " "username_value, password_element, " - "submit_element, signon_realm))", - NULL, NULL, NULL) != SQLITE_OK) { + "submit_element, signon_realm))")) { NOTREACHED(); return false; } - if (sqlite3_exec(db_, "CREATE INDEX logins_signon ON " - "logins (signon_realm)", - NULL, NULL, NULL) != SQLITE_OK) { + if (!db_.Execute("CREATE INDEX logins_signon ON logins (signon_realm)")) { NOTREACHED(); return false; } } #if defined(OS_WIN) - if (!DoesSqliteTableExist(db_, "ie7_logins")) { - // First time - if (sqlite3_exec(db_, "CREATE TABLE ie7_logins (" + if (!db_.DoesTableExist("ie7_logins")) { + if (!db_.Execute("CREATE TABLE ie7_logins (" "url_hash VARCHAR NOT NULL, " "password_value BLOB, " "date_created INTEGER NOT NULL," "UNIQUE " - "(url_hash))", - NULL, NULL, NULL) != SQLITE_OK) { + "(url_hash))")) { NOTREACHED(); return false; } - if (sqlite3_exec(db_, "CREATE INDEX ie7_logins_hash ON " - "ie7_logins (url_hash)", - NULL, NULL, NULL) != SQLITE_OK) { + if (!db_.Execute("CREATE INDEX ie7_logins_hash ON " + "ie7_logins (url_hash)")) { NOTREACHED(); return false; } @@ -369,29 +344,22 @@ bool WebDatabase::InitLoginsTable() { } bool WebDatabase::InitAutofillTable() { - if (!DoesSqliteTableExist(db_, "autofill")) { - if (sqlite3_exec(db_, - "CREATE TABLE autofill (" + if (!db_.DoesTableExist("autofill")) { + if (!db_.Execute("CREATE TABLE autofill (" "name VARCHAR, " "value VARCHAR, " "value_lower VARCHAR, " "pair_id INTEGER PRIMARY KEY, " - "count INTEGER DEFAULT 1)", - NULL, NULL, NULL) != SQLITE_OK) { + "count INTEGER DEFAULT 1)")) { NOTREACHED(); return false; } - if (sqlite3_exec(db_, - "CREATE INDEX autofill_name ON " - "autofill (name)", - NULL, NULL, NULL) != SQLITE_OK) { + if (!db_.Execute("CREATE INDEX autofill_name ON autofill (name)")) { NOTREACHED(); return false; } - if (sqlite3_exec(db_, - "CREATE INDEX autofill_name_value_lower ON " - "autofill (name, value_lower)", - NULL, NULL, NULL) != SQLITE_OK) { + if (!db_.Execute("CREATE INDEX autofill_name_value_lower ON " + "autofill (name, value_lower)")) { NOTREACHED(); return false; } @@ -400,34 +368,29 @@ bool WebDatabase::InitAutofillTable() { } bool WebDatabase::InitAutofillDatesTable() { - if (!DoesSqliteTableExist(db_, "autofill_dates")) { - if (sqlite3_exec(db_, - "CREATE TABLE autofill_dates ( " + if (!db_.DoesTableExist("autofill_dates")) { + if (!db_.Execute("CREATE TABLE autofill_dates ( " "pair_id INTEGER DEFAULT 0, " - "date_created INTEGER DEFAULT 0)", - NULL, NULL, NULL) != SQLITE_OK) { + "date_created INTEGER DEFAULT 0)")) { NOTREACHED(); return false; } - if (sqlite3_exec(db_, - "CREATE INDEX autofill_dates_pair_id ON " - "autofill_dates (pair_id)", - NULL, NULL, NULL) != SQLITE_OK) { - NOTREACHED(); - return false; + if (!db_.Execute("CREATE INDEX autofill_dates_pair_id ON " + "autofill_dates (pair_id)")) { + NOTREACHED(); + return false; } } return true; } bool WebDatabase::InitWebAppIconsTable() { - if (!DoesSqliteTableExist(db_, "web_app_icons")) { - if (sqlite3_exec(db_, "CREATE TABLE web_app_icons (" + if (!db_.DoesTableExist("web_app_icons")) { + if (!db_.Execute("CREATE TABLE web_app_icons (" "url LONGVARCHAR," "width int," "height int," - "image BLOB, UNIQUE (url, width, height))", - NULL, NULL, NULL) != SQLITE_OK) { + "image BLOB, UNIQUE (url, width, height))")) { NOTREACHED(); return false; } @@ -436,16 +399,14 @@ bool WebDatabase::InitWebAppIconsTable() { } bool WebDatabase::InitWebAppsTable() { - if (!DoesSqliteTableExist(db_, "web_apps")) { - if (sqlite3_exec(db_, "CREATE TABLE web_apps (" + if (!db_.DoesTableExist("web_apps")) { + if (!db_.Execute("CREATE TABLE web_apps (" "url LONGVARCHAR UNIQUE," - "has_all_images INTEGER NOT NULL)", - NULL, NULL, NULL) != SQLITE_OK) { + "has_all_images INTEGER NOT NULL)")) { NOTREACHED(); return false; } - if (sqlite3_exec(db_, "CREATE INDEX web_apps_url_index ON " - "web_apps (url)", NULL, NULL, NULL) != SQLITE_OK) { + if (!db_.Execute("CREATE INDEX web_apps_url_index ON web_apps (url)")) { NOTREACHED(); return false; } @@ -453,56 +414,55 @@ bool WebDatabase::InitWebAppsTable() { return true; } -static void BindURLToStatement(const TemplateURL& url, SQLStatement* s) { - s->bind_wstring(0, url.short_name()); - s->bind_wstring(1, url.keyword()); +static void BindURLToStatement(const TemplateURL& url, sql::Statement* s) { + s->BindString(0, WideToUTF8(url.short_name())); + s->BindString(1, WideToUTF8(url.keyword())); GURL favicon_url = url.GetFavIconURL(); if (!favicon_url.is_valid()) { - s->bind_string(2, ""); + s->BindString(2, std::string()); } else { - s->bind_string(2, history::HistoryDatabase::GURLToDatabaseURL( + s->BindString(2, history::HistoryDatabase::GURLToDatabaseURL( url.GetFavIconURL())); } if (url.url()) - s->bind_wstring(3, url.url()->url()); + s->BindString(3, WideToUTF8(url.url()->url())); else - s->bind_wstring(3, std::wstring()); - s->bind_int(4, url.safe_for_autoreplace() ? 1 : 0); + s->BindString(3, std::string()); + s->BindInt(4, url.safe_for_autoreplace() ? 1 : 0); if (!url.originating_url().is_valid()) { - s->bind_string(5, std::string()); + s->BindString(5, std::string()); } else { - s->bind_string(5, history::HistoryDatabase::GURLToDatabaseURL( + s->BindString(5, history::HistoryDatabase::GURLToDatabaseURL( url.originating_url())); } - s->bind_int64(6, url.date_created().ToTimeT()); - s->bind_int(7, url.usage_count()); - s->bind_string(8, JoinStrings(";", url.input_encodings())); - s->bind_int(9, url.show_in_default_list() ? 1 : 0); + s->BindInt64(6, url.date_created().ToTimeT()); + s->BindInt(7, url.usage_count()); + s->BindString(8, JoinStrings(";", url.input_encodings())); + s->BindInt(9, url.show_in_default_list() ? 1 : 0); if (url.suggestions_url()) - s->bind_wstring(10, url.suggestions_url()->url()); + s->BindString(10, WideToUTF8(url.suggestions_url()->url())); else - s->bind_wstring(10, std::wstring()); - s->bind_int(11, url.prepopulate_id()); - s->bind_int(12, url.autogenerate_keyword() ? 1 : 0); + s->BindString(10, std::string()); + s->BindInt(11, url.prepopulate_id()); + s->BindInt(12, url.autogenerate_keyword() ? 1 : 0); } bool WebDatabase::AddKeyword(const TemplateURL& url) { DCHECK(url.id()); - SQLStatement s; - if (s.prepare(db_, - "INSERT INTO keywords " - "(short_name, keyword, favicon_url, url, safe_for_autoreplace, " - "originating_url, date_created, usage_count, input_encodings, " - "show_in_default_list, suggest_url, prepopulate_id, " - "autogenerate_keyword, id) VALUES " - "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") - != SQLITE_OK) { + sql::Statement s(db_.GetCachedStatement(SQL_FROM_HERE, + "INSERT INTO keywords " + "(short_name, keyword, favicon_url, url, safe_for_autoreplace, " + "originating_url, date_created, usage_count, input_encodings, " + "show_in_default_list, suggest_url, prepopulate_id, " + "autogenerate_keyword, id) VALUES " + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?)")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } BindURLToStatement(url, &s); - s.bind_int64(13, url.id()); - if (s.step() != SQLITE_DONE) { + s.BindInt64(13, url.id()); + if (!s.Run()) { NOTREACHED(); return false; } @@ -511,92 +471,89 @@ bool WebDatabase::AddKeyword(const TemplateURL& url) { bool WebDatabase::RemoveKeyword(TemplateURL::IDType id) { DCHECK(id); - SQLStatement s; - if (s.prepare(db_, - "DELETE FROM keywords WHERE id = ?") != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement("DELETE FROM keywords WHERE id = ?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_int64(0, id); - return s.step() == SQLITE_DONE; + s.BindInt64(0, id); + return s.Run(); } -bool WebDatabase::GetKeywords(std::vector<TemplateURL*>* urls) const { - SQLStatement s; - if (s.prepare(db_, - "SELECT id, short_name, keyword, favicon_url, url, " - "safe_for_autoreplace, originating_url, date_created, " - "usage_count, input_encodings, show_in_default_list, " - "suggest_url, prepopulate_id, autogenerate_keyword " - "FROM keywords ORDER BY id ASC") != SQLITE_OK) { +bool WebDatabase::GetKeywords(std::vector<TemplateURL*>* urls) { + sql::Statement s(db_.GetUniqueStatement( + "SELECT id, short_name, keyword, favicon_url, url, " + "safe_for_autoreplace, originating_url, date_created, " + "usage_count, input_encodings, show_in_default_list, " + "suggest_url, prepopulate_id, autogenerate_keyword " + "FROM keywords ORDER BY id ASC")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - int result; - while ((result = s.step()) == SQLITE_ROW) { + while (s.Step()) { TemplateURL* template_url = new TemplateURL(); - std::wstring tmp; - template_url->set_id(s.column_int64(0)); + template_url->set_id(s.ColumnInt64(0)); - s.column_wstring(1, &tmp); + std::string tmp; + tmp = s.ColumnString(1); DCHECK(!tmp.empty()); - template_url->set_short_name(tmp); + template_url->set_short_name(UTF8ToWide(tmp)); - s.column_wstring(2, &tmp); - template_url->set_keyword(tmp); + tmp = s.ColumnString(2); + template_url->set_keyword(UTF8ToWide(tmp)); - s.column_wstring(3, &tmp); + tmp = s.ColumnString(3); if (!tmp.empty()) - template_url->SetFavIconURL(GURL(WideToUTF8(tmp))); + template_url->SetFavIconURL(GURL(tmp)); - s.column_wstring(4, &tmp); - template_url->SetURL(tmp, 0, 0); + tmp = s.ColumnString(4); + template_url->SetURL(UTF8ToWide(tmp), 0, 0); - template_url->set_safe_for_autoreplace(s.column_int(5) == 1); + template_url->set_safe_for_autoreplace(s.ColumnInt(5) == 1); - s.column_wstring(6, &tmp); + tmp = s.ColumnString(6); if (!tmp.empty()) - template_url->set_originating_url(GURL(WideToUTF8(tmp))); + template_url->set_originating_url(GURL(tmp)); - template_url->set_date_created(Time::FromTimeT(s.column_int64(7))); + template_url->set_date_created(Time::FromTimeT(s.ColumnInt64(7))); - template_url->set_usage_count(s.column_int(8)); + template_url->set_usage_count(s.ColumnInt(8)); std::vector<std::string> encodings; - SplitString(s.column_string(9), ';', &encodings); + SplitString(s.ColumnString(9), ';', &encodings); template_url->set_input_encodings(encodings); - template_url->set_show_in_default_list(s.column_int(10) == 1); + template_url->set_show_in_default_list(s.ColumnInt(10) == 1); - s.column_wstring(11, &tmp); - template_url->SetSuggestionsURL(tmp, 0, 0); + tmp = s.ColumnString(11); + template_url->SetSuggestionsURL(UTF8ToWide(tmp), 0, 0); - template_url->set_prepopulate_id(s.column_int(12)); + template_url->set_prepopulate_id(s.ColumnInt(12)); - template_url->set_autogenerate_keyword(s.column_int(13) == 1); + template_url->set_autogenerate_keyword(s.ColumnInt(13) == 1); urls->push_back(template_url); } - return result == SQLITE_DONE; + return s.Succeeded(); } bool WebDatabase::UpdateKeyword(const TemplateURL& url) { DCHECK(url.id()); - SQLStatement s; - if (s.prepare(db_, - "UPDATE keywords " - "SET short_name=?, keyword=?, favicon_url=?, url=?, " - "safe_for_autoreplace=?, originating_url=?, date_created=?, " - "usage_count=?, input_encodings=?, show_in_default_list=?, " - "suggest_url=?, prepopulate_id=?, autogenerate_keyword=? " - "WHERE id=?") - != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement( + "UPDATE keywords " + "SET short_name=?, keyword=?, favicon_url=?, url=?, " + "safe_for_autoreplace=?, originating_url=?, date_created=?, " + "usage_count=?, input_encodings=?, show_in_default_list=?, " + "suggest_url=?, prepopulate_id=?, autogenerate_keyword=? " + "WHERE id=?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } BindURLToStatement(url, &s); - s.bind_int64(13, url.id()); - return s.step() == SQLITE_DONE; + s.BindInt64(13, url.id()); + return s.Run(); } bool WebDatabase::SetDefaultSearchProviderID(int64 id) { @@ -620,37 +577,37 @@ int WebDatabase::GetBuitinKeywordVersion() { } bool WebDatabase::AddLogin(const PasswordForm& form) { - SQLStatement s; - std::string encrypted_password; - if (s.prepare(db_, - "INSERT OR REPLACE INTO logins " - "(origin_url, action_url, username_element, username_value, " - " password_element, password_value, submit_element, " - " signon_realm, ssl_valid, preferred, date_created, " - " blacklisted_by_user, scheme) " - "VALUES " - "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement( + "INSERT OR REPLACE INTO logins " + "(origin_url, action_url, username_element, username_value, " + " password_element, password_value, submit_element, " + " signon_realm, ssl_valid, preferred, date_created, " + " blacklisted_by_user, scheme) " + "VALUES " + "(?,?,?,?,?,?,?,?,?,?,?,?,?)")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_string(0, form.origin.spec()); - s.bind_string(1, form.action.spec()); - s.bind_wstring(2, form.username_element); - s.bind_wstring(3, form.username_value); - s.bind_wstring(4, form.password_element); + std::string encrypted_password; + s.BindString(0, form.origin.spec()); + s.BindString(1, form.action.spec()); + s.BindString(2, WideToUTF8(form.username_element)); + s.BindString(3, WideToUTF8(form.username_value)); + s.BindString(4, WideToUTF8(form.password_element)); Encryptor::EncryptString16(WideToUTF16Hack(form.password_value), &encrypted_password); - s.bind_blob(5, encrypted_password.data(), - static_cast<int>(encrypted_password.length())); - s.bind_wstring(6, form.submit_element); - s.bind_string(7, form.signon_realm); - s.bind_int(8, form.ssl_valid); - s.bind_int(9, form.preferred); - s.bind_int64(10, form.date_created.ToTimeT()); - s.bind_int(11, form.blacklisted_by_user); - s.bind_int(12, form.scheme); - if (s.step() != SQLITE_DONE) { + s.BindBlob(5, encrypted_password.data(), + static_cast<int>(encrypted_password.length())); + s.BindString(6, WideToUTF8(form.submit_element)); + s.BindString(7, form.signon_realm); + s.BindInt(8, form.ssl_valid); + s.BindInt(9, form.preferred); + s.BindInt64(10, form.date_created.ToTimeT()); + s.BindInt(11, form.blacklisted_by_user); + s.BindInt(12, form.scheme); + if (!s.Run()) { NOTREACHED(); return false; } @@ -658,36 +615,37 @@ bool WebDatabase::AddLogin(const PasswordForm& form) { } bool WebDatabase::UpdateLogin(const PasswordForm& form) { - SQLStatement s; - std::string encrypted_password; - if (s.prepare(db_, "UPDATE logins SET " - "action_url = ?, " - "password_value = ?, " - "ssl_valid = ?, " - "preferred = ? " - "WHERE origin_url = ? AND " - "username_element = ? AND " - "username_value = ? AND " - "password_element = ? AND " - "signon_realm = ?") != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement( + "UPDATE logins SET " + "action_url = ?, " + "password_value = ?, " + "ssl_valid = ?, " + "preferred = ? " + "WHERE origin_url = ? AND " + "username_element = ? AND " + "username_value = ? AND " + "password_element = ? AND " + "signon_realm = ?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_string(0, form.action.spec()); + s.BindString(0, form.action.spec()); + std::string encrypted_password; Encryptor::EncryptString16(WideToUTF16Hack(form.password_value), &encrypted_password); - s.bind_blob(1, encrypted_password.data(), - static_cast<int>(encrypted_password.length())); - s.bind_int(2, form.ssl_valid); - s.bind_int(3, form.preferred); - s.bind_string(4, form.origin.spec()); - s.bind_wstring(5, form.username_element); - s.bind_wstring(6, form.username_value); - s.bind_wstring(7, form.password_element); - s.bind_string(8, form.signon_realm); - - if (s.step() != SQLITE_DONE) { + s.BindBlob(1, encrypted_password.data(), + static_cast<int>(encrypted_password.length())); + s.BindInt(2, form.ssl_valid); + s.BindInt(3, form.preferred); + s.BindString(4, form.origin.spec()); + s.BindString(5, WideToUTF8(form.username_element)); + s.BindString(6, WideToUTF8(form.username_value)); + s.BindString(7, WideToUTF8(form.password_element)); + s.BindString(8, form.signon_realm); + + if (!s.Run()) { NOTREACHED(); return false; } @@ -695,127 +653,130 @@ bool WebDatabase::UpdateLogin(const PasswordForm& form) { } bool WebDatabase::RemoveLogin(const PasswordForm& form) { - SQLStatement s; // Remove a login by UNIQUE-constrained fields. - if (s.prepare(db_, - "DELETE FROM logins WHERE " - "origin_url = ? AND " - "username_element = ? AND " - "username_value = ? AND " - "password_element = ? AND " - "submit_element = ? AND " - "signon_realm = ? ") != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement( + "DELETE FROM logins WHERE " + "origin_url = ? AND " + "username_element = ? AND " + "username_value = ? AND " + "password_element = ? AND " + "submit_element = ? AND " + "signon_realm = ?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_string(0, form.origin.spec()); - s.bind_wstring(1, form.username_element); - s.bind_wstring(2, form.username_value); - s.bind_wstring(3, form.password_element); - s.bind_wstring(4, form.submit_element); - s.bind_string(5, form.signon_realm); - - if (s.step() != SQLITE_DONE) { + s.BindString(0, form.origin.spec()); + s.BindString(1, WideToUTF8(form.username_element)); + s.BindString(2, WideToUTF8(form.username_value)); + s.BindString(3, WideToUTF8(form.password_element)); + s.BindString(4, WideToUTF8(form.submit_element)); + s.BindString(5, form.signon_realm); + + if (!s.Run()) { NOTREACHED(); return false; } return true; } -bool WebDatabase::RemoveLoginsCreatedBetween(const Time delete_begin, - const Time delete_end) { - SQLStatement s1; - if (s1.prepare(db_, - "DELETE FROM logins WHERE " - "date_created >= ? AND date_created < ?") != SQLITE_OK) { +bool WebDatabase::RemoveLoginsCreatedBetween(base::Time delete_begin, + base::Time delete_end) { + sql::Statement s1(db_.GetUniqueStatement( + "DELETE FROM logins WHERE " + "date_created >= ? AND date_created < ?")); + if (!s1) { NOTREACHED() << "Statement 1 prepare failed"; return false; } - s1.bind_int64(0, delete_begin.ToTimeT()); - s1.bind_int64(1, - delete_end.is_null() ? - std::numeric_limits<int64>::max() : - delete_end.ToTimeT()); - bool success = s1.step() == SQLITE_DONE; + s1.BindInt64(0, delete_begin.ToTimeT()); + s1.BindInt64(1, + delete_end.is_null() ? + std::numeric_limits<int64>::max() : + delete_end.ToTimeT()); + bool success = s1.Run(); #if defined(OS_WIN) - SQLStatement s2; - if (s2.prepare(db_, - "DELETE FROM ie7_logins WHERE " - "date_created >= ? AND date_created < ?") != SQLITE_OK) { + sql::Statement s2(db_.GetUniqueStatement( + "DELETE FROM ie7_logins WHERE date_created >= ? AND date_created < ?")); + if (!s2) { NOTREACHED() << "Statement 2 prepare failed"; return false; } - s2.bind_int64(0, delete_begin.ToTimeT()); - s2.bind_int64(1, - delete_end.is_null() ? - std::numeric_limits<int64>::max() : - delete_end.ToTimeT()); - success = success && (s2.step() == SQLITE_DONE); + s2.BindInt64(0, delete_begin.ToTimeT()); + s2.BindInt64(1, + delete_end.is_null() ? + std::numeric_limits<int64>::max() : + delete_end.ToTimeT()); + success = success && s2.Run(); #endif return success; } static void InitPasswordFormFromStatement(PasswordForm* form, - SQLStatement* s) { - std::string encrypted_password; + sql::Statement* s) { std::string tmp; string16 decrypted_password; - s->column_string(0, &tmp); + tmp = s->ColumnString(0); form->origin = GURL(tmp); - s->column_string(1, &tmp); + tmp = s->ColumnString(1); form->action = GURL(tmp); - s->column_wstring(2, &form->username_element); - s->column_wstring(3, &form->username_value); - s->column_wstring(4, &form->password_element); - s->column_blob_as_string(5, &encrypted_password); - Encryptor::DecryptString16(encrypted_password, &decrypted_password); + form->username_element = UTF8ToWide(s->ColumnString(2)); + form->username_value = UTF8ToWide(s->ColumnString(3)); + form->password_element = UTF8ToWide(s->ColumnString(4)); + + int encrypted_password_len = s->ColumnByteLength(5); + std::string encrypted_password; + if (encrypted_password_len) { + encrypted_password.resize(encrypted_password_len); + memcpy(&encrypted_password[0], s->ColumnBlob(5), encrypted_password_len); + Encryptor::DecryptString16(encrypted_password, &decrypted_password); + } + form->password_value = UTF16ToWideHack(decrypted_password); - s->column_wstring(6, &form->submit_element); - s->column_string(7, &tmp); + form->submit_element = UTF8ToWide(s->ColumnString(6)); + tmp = s->ColumnString(7); form->signon_realm = tmp; - form->ssl_valid = (s->column_int(8) > 0); - form->preferred = (s->column_int(9) > 0); - form->date_created = Time::FromTimeT(s->column_int64(10)); - form->blacklisted_by_user = (s->column_int(11) > 0); - int scheme_int = s->column_int(12); + form->ssl_valid = (s->ColumnInt(8) > 0); + form->preferred = (s->ColumnInt(9) > 0); + form->date_created = Time::FromTimeT(s->ColumnInt64(10)); + form->blacklisted_by_user = (s->ColumnInt(11) > 0); + int scheme_int = s->ColumnInt(12); DCHECK((scheme_int >= 0) && (scheme_int <= PasswordForm::SCHEME_OTHER)); form->scheme = static_cast<PasswordForm::Scheme>(scheme_int); } bool WebDatabase::GetLogins(const PasswordForm& form, - std::vector<PasswordForm*>* forms) const { + std::vector<PasswordForm*>* forms) { DCHECK(forms); - SQLStatement s; - if (s.prepare(db_, + sql::Statement s(db_.GetUniqueStatement( "SELECT origin_url, action_url, " "username_element, username_value, " "password_element, password_value, " "submit_element, signon_realm, " "ssl_valid, preferred, " "date_created, blacklisted_by_user, scheme FROM logins " - "WHERE signon_realm == ? ") != SQLITE_OK) { + "WHERE signon_realm == ?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_string(0, form.signon_realm); + s.BindString(0, form.signon_realm); - int result; - while ((result = s.step()) == SQLITE_ROW) { + while (s.Step()) { PasswordForm* new_form = new PasswordForm(); InitPasswordFormFromStatement(new_form, &s); forms->push_back(new_form); } - return result == SQLITE_DONE; + return s.Succeeded(); } bool WebDatabase::GetAllLogins(std::vector<PasswordForm*>* forms, - bool include_blacklisted) const { + bool include_blacklisted) { DCHECK(forms); - SQLStatement s; std::string stmt = "SELECT origin_url, action_url, " "username_element, username_value, " "password_element, password_value, " @@ -825,19 +786,19 @@ bool WebDatabase::GetAllLogins(std::vector<PasswordForm*>* forms, stmt.append("WHERE blacklisted_by_user == 0 "); stmt.append("ORDER BY origin_url"); - if (s.prepare(db_, stmt.c_str()) != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement(stmt.c_str())); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - int result; - while ((result = s.step()) == SQLITE_ROW) { + while (s.Step()) { PasswordForm* new_form = new PasswordForm(); InitPasswordFormFromStatement(new_form, &s); forms->push_back(new_form); } - return result == SQLITE_DONE; + return s.Succeeded(); } bool WebDatabase::AddAutofillFormElements( @@ -853,18 +814,16 @@ bool WebDatabase::AddAutofillFormElements( } bool WebDatabase::ClearAutofillEmptyValueElements() { - SQLStatement s; - - if (s.prepare(db_, "SELECT pair_id FROM autofill " - "WHERE TRIM(value)= \"\"") != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement( + "SELECT pair_id FROM autofill WHERE TRIM(value)= \"\"")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } std::set<int64> ids; - int result; - while ((result = s.step()) == SQLITE_ROW) - ids.insert(s.column_int64(0)); + while (s.Step()) + ids.insert(s.ColumnInt64(0)); bool success = true; for (std::set<int64>::const_iterator iter = ids.begin(); iter != ids.end(); @@ -877,93 +836,84 @@ bool WebDatabase::ClearAutofillEmptyValueElements() { } bool WebDatabase::GetIDAndCountOfFormElement( - const AutofillForm::Element& element, int64* pair_id, int* count) const { - SQLStatement s; - - if (s.prepare(db_, "SELECT pair_id, count FROM autofill " - " WHERE name = ? AND value = ?") != SQLITE_OK) { + const AutofillForm::Element& element, + int64* pair_id, + int* count) { + sql::Statement s(db_.GetUniqueStatement( + "SELECT pair_id, count FROM autofill " + "WHERE name = ? AND value = ?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_wstring(0, element.name); - s.bind_wstring(1, element.value); - - int result; + s.BindString(0, WideToUTF8(element.name)); + s.BindString(1, WideToUTF8(element.value)); *count = 0; - if ((result = s.step()) == SQLITE_ROW) { - *pair_id = s.column_int64(0); - *count = s.column_int(1); + if (s.Step()) { + *pair_id = s.ColumnInt64(0); + *count = s.ColumnInt(1); } return true; } -bool WebDatabase::GetCountOfFormElement(int64 pair_id, int* count) const { - SQLStatement s; - - if (s.prepare(db_, "SELECT count FROM autofill " - " WHERE pair_id = ?") != SQLITE_OK) { +bool WebDatabase::GetCountOfFormElement(int64 pair_id, int* count) { + sql::Statement s(db_.GetUniqueStatement( + "SELECT count FROM autofill WHERE pair_id = ?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_int64(0, pair_id); + s.BindInt64(0, pair_id); - int result; - if ((result = s.step()) == SQLITE_ROW) { - *count = s.column_int(0); - } else { - return false; + if (s.Step()) { + *count = s.ColumnInt(0); + return true; } - - return true; + return false; } bool WebDatabase::InsertFormElement(const AutofillForm::Element& element, int64* pair_id) { - SQLStatement s; - - if (s.prepare(db_, "INSERT INTO autofill " - "(name, value, value_lower) " - "VALUES (?, ?, ?)") - != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement( + "INSERT INTO autofill (name, value, value_lower) VALUES (?,?,?)")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_wstring(0, element.name); - s.bind_wstring(1, element.value); - s.bind_wstring(2, l10n_util::ToLower(element.value)); + s.BindString(0, WideToUTF8(element.name)); + s.BindString(1, WideToUTF8(element.value)); + s.BindString(2, UTF16ToUTF8( + l10n_util::ToLower(WideToUTF16Hack(element.value)))); - if (s.step() != SQLITE_DONE) { + if (!s.Run()) { NOTREACHED(); return false; } - *pair_id = sqlite3_last_insert_rowid(db_); - + *pair_id = db_.GetLastInsertRowId(); return true; } bool WebDatabase::InsertPairIDAndDate(int64 pair_id, - const Time date_created) { - SQLStatement s; - - if (s.prepare(db_, - "INSERT INTO autofill_dates " - "(pair_id, date_created) VALUES (?, ?)") - != SQLITE_OK) { + base::Time date_created) { + sql::Statement s(db_.GetUniqueStatement( + "INSERT INTO autofill_dates " + "(pair_id, date_created) VALUES (?, ?)")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_int64(0, pair_id); - s.bind_int64(1, date_created.ToTimeT()); + s.BindInt64(0, pair_id); + s.BindInt64(1, date_created.ToTimeT()); - if (s.step() != SQLITE_DONE) { + if (!s.Run()) { NOTREACHED(); return false; } @@ -972,20 +922,16 @@ bool WebDatabase::InsertPairIDAndDate(int64 pair_id, } bool WebDatabase::SetCountOfFormElement(int64 pair_id, int count) { - SQLStatement s; - - if (s.prepare(db_, - "UPDATE autofill SET count = ? " - "WHERE pair_id = ?") - != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement( + "UPDATE autofill SET count = ? WHERE pair_id = ?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_int(0, count); - s.bind_int64(1, pair_id); - - if (s.step() != SQLITE_DONE) { + s.BindInt(0, count); + s.BindInt64(1, pair_id); + if (!s.Run()) { NOTREACHED(); return false; } @@ -994,7 +940,6 @@ bool WebDatabase::SetCountOfFormElement(int64 pair_id, int count) { } bool WebDatabase::AddAutofillFormElement(const AutofillForm::Element& element) { - SQLStatement s; int count = 0; int64 pair_id; @@ -1009,73 +954,74 @@ bool WebDatabase::AddAutofillFormElement(const AutofillForm::Element& element) { } bool WebDatabase::GetFormValuesForElementName(const std::wstring& name, - const std::wstring& prefix, - std::vector<std::wstring>* values, - int limit) const { + const std::wstring& prefix, + std::vector<std::wstring>* values, + int limit) { DCHECK(values); - SQLStatement s; + sql::Statement s; if (prefix.empty()) { - if (s.prepare(db_, "SELECT value FROM autofill " - "WHERE name = ? " - "ORDER BY count DESC " - "LIMIT ?") != SQLITE_OK) { + s.Assign(db_.GetUniqueStatement( + "SELECT value FROM autofill " + "WHERE name = ? " + "ORDER BY count DESC " + "LIMIT ?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_wstring(0, name); - s.bind_int(1, limit); + s.BindString(0, WideToUTF8(name)); + s.BindInt(1, limit); } else { - std::wstring prefix_lower = l10n_util::ToLower(prefix); - std::wstring next_prefix = prefix_lower; + string16 prefix_lower = l10n_util::ToLower(WideToUTF16Hack(prefix)); + string16 next_prefix = prefix_lower; next_prefix[next_prefix.length() - 1]++; - if (s.prepare(db_, "SELECT value FROM autofill " - "WHERE name = ? AND " - "value_lower >= ? AND " - "value_lower < ? " - "ORDER BY count DESC " - "LIMIT ?") != SQLITE_OK) { + s.Assign(db_.GetUniqueStatement( + "SELECT value FROM autofill " + "WHERE name = ? AND " + "value_lower >= ? AND " + "value_lower < ? " + "ORDER BY count DESC " + "LIMIT ?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_wstring(0, name); - s.bind_wstring(1, prefix_lower); - s.bind_wstring(2, next_prefix); - s.bind_int(3, limit); + s.BindString(0, WideToUTF8(name)); + s.BindString(1, UTF16ToUTF8(prefix_lower)); + s.BindString(2, UTF16ToUTF8(next_prefix)); + s.BindInt(3, limit); } values->clear(); - int result; - while ((result = s.step()) == SQLITE_ROW) - values->push_back(s.column_wstring(0)); - - return result == SQLITE_DONE; + while (s.Step()) + values->push_back(UTF8ToWide(s.ColumnString(0))); + return s.Succeeded(); } -bool WebDatabase::RemoveFormElementsAddedBetween(const Time delete_begin, - const Time delete_end) { - SQLStatement s; - if (s.prepare(db_, - "SELECT DISTINCT pair_id FROM autofill_dates WHERE " - "date_created >= ? AND date_created < ?") != SQLITE_OK) { +bool WebDatabase::RemoveFormElementsAddedBetween(base::Time delete_begin, + base::Time delete_end) { + sql::Statement s(db_.GetUniqueStatement( + "SELECT DISTINCT pair_id FROM autofill_dates " + "WHERE date_created >= ? AND date_created < ?")); + if (!s) { NOTREACHED() << "Statement 1 prepare failed"; return false; } - s.bind_int64(0, delete_begin.ToTimeT()); - s.bind_int64(1, - delete_end.is_null() ? - std::numeric_limits<int64>::max() : - delete_end.ToTimeT()); + s.BindInt64(0, delete_begin.ToTimeT()); + s.BindInt64(1, + delete_end.is_null() ? + std::numeric_limits<int64>::max() : + delete_end.ToTimeT()); std::vector<int64> pair_ids; - int result; - while ((result = s.step()) == SQLITE_ROW) - pair_ids.push_back(s.column_int64(0)); + while (s.Step()) + pair_ids.push_back(s.ColumnInt64(0)); - if (result != SQLITE_DONE) { + if (!s.Succeeded()) { NOTREACHED(); return false; } @@ -1099,21 +1045,21 @@ bool WebDatabase::RemoveFormElementForTimeRange(int64 pair_id, const Time delete_begin, const Time delete_end, int* how_many) { - SQLStatement s; - if (s.prepare(db_, - "DELETE FROM autofill_dates WHERE pair_id = ? AND " - "date_created >= ? AND date_created < ?") != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement( + "DELETE FROM autofill_dates WHERE pair_id = ? AND " + "date_created >= ? AND date_created < ?")); + if (!s) { NOTREACHED() << "Statement 1 prepare failed"; return false; } - s.bind_int64(0, pair_id); - s.bind_int64(1, delete_begin.is_null() ? 0 : delete_begin.ToTimeT()); - s.bind_int64(2, delete_end.is_null() ? std::numeric_limits<int64>::max() : - delete_end.ToTimeT()); + s.BindInt64(0, pair_id); + s.BindInt64(1, delete_begin.is_null() ? 0 : delete_begin.ToTimeT()); + s.BindInt64(2, delete_end.is_null() ? std::numeric_limits<int64>::max() : + delete_end.ToTimeT()); - bool result = (s.step() == SQLITE_DONE); + bool result = s.Run(); if (how_many) - *how_many = sqlite3_changes(db_); + *how_many = db_.GetLastChangeCount(); return result; } @@ -1121,21 +1067,18 @@ bool WebDatabase::RemoveFormElementForTimeRange(int64 pair_id, bool WebDatabase::RemoveFormElement(const std::wstring& name, const std::wstring& value) { // Find the id for that pair. - SQLStatement s; - if (s.prepare(db_, - "SELECT pair_id FROM autofill WHERE name = ? AND value= ?") != - SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement( + "SELECT pair_id FROM autofill WHERE name = ? AND value= ?")); + if (!s) { NOTREACHED() << "Statement 1 prepare failed"; return false; } - s.bind_wstring(0, name); - s.bind_wstring(1, value); - - int result = s.step(); - if (result != SQLITE_ROW) - return false; + s.BindString(0, WideToUTF8(name)); + s.BindString(1, WideToUTF8(value)); - return RemoveFormElementForID(s.column_int64(0)); + if (s.Step()) + return RemoveFormElementForID(s.ColumnInt64(0)); + return false; } bool WebDatabase::AddToCountOfFormElement(int64 pair_id, int delta) { @@ -1155,17 +1098,18 @@ bool WebDatabase::AddToCountOfFormElement(int64 pair_id, int delta) { } bool WebDatabase::RemoveFormElementForID(int64 pair_id) { - SQLStatement s; - if (s.prepare(db_, - "DELETE FROM autofill WHERE pair_id = ?") != SQLITE_OK) { + sql::Statement s(db_.GetUniqueStatement( + "DELETE FROM autofill WHERE pair_id = ?")); + if (!s) { NOTREACHED() << "Statement prepare failed"; return false; } - s.bind_int64(0, pair_id); - if (s.step() != SQLITE_DONE) - return false; - - return RemoveFormElementForTimeRange(pair_id, Time(), Time(), NULL); + s.BindInt64(0, pair_id); + if (s.Run()) { + return RemoveFormElementForTimeRange(pair_id, base::Time(), base::Time(), + NULL); + } + return false; } void WebDatabase::MigrateOldVersionsAsNeeded() { @@ -1184,9 +1128,8 @@ void WebDatabase::MigrateOldVersionsAsNeeded() { case 20: // Add the autogenerate_keyword column. - if (sqlite3_exec(db_, - "ALTER TABLE keywords ADD COLUMN autogenerate_keyword " - "INTEGER DEFAULT 0", NULL, NULL, NULL) != SQLITE_OK) { + if (!db_.Execute("ALTER TABLE keywords ADD COLUMN autogenerate_keyword " + "INTEGER DEFAULT 0")) { NOTREACHED(); LOG(WARNING) << "Unable to update web database to version 21."; return; diff --git a/chrome/browser/webdata/web_database.h b/chrome/browser/webdata/web_database.h index 7ef4f03..b966938 100644 --- a/chrome/browser/webdata/web_database.h +++ b/chrome/browser/webdata/web_database.h @@ -1,13 +1,15 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_WEBDATA_WEB_DATABASE_H__ -#define CHROME_BROWSER_WEBDATA_WEB_DATABASE_H__ +#ifndef CHROME_BROWSER_WEBDATA_WEB_DATABASE_H_ +#define CHROME_BROWSER_WEBDATA_WEB_DATABASE_H_ #include <string> #include <vector> +#include "app/sql/connection.h" +#include "app/sql/meta_table.h" #include "base/basictypes.h" #include "chrome/browser/meta_table_helper.h" #include "chrome/browser/search_engines/template_url.h" @@ -16,6 +18,8 @@ #include "testing/gtest/include/gtest/gtest_prod.h" #include "webkit/glue/autofill_form.h" +class FilePath; + namespace base { class Time; } @@ -40,7 +44,7 @@ class WebDatabase { // Initialize the database given a name. The name defines where the sqlite // file is. If false is returned, no other method should be called. - bool Init(const std::wstring& db_name); + bool Init(const FilePath& db_name); // Transactions management void BeginTransaction(); @@ -63,7 +67,7 @@ class WebDatabase { // Loads the keywords into the specified vector. It's up to the caller to // delete the returned objects. // Returns true on success. - bool GetKeywords(std::vector<TemplateURL*>* urls) const; + bool GetKeywords(std::vector<TemplateURL*>* urls); // Updates the database values for the specified url. // Returns true on success. @@ -106,21 +110,21 @@ class WebDatabase { // Removes all logins created from |delete_begin| onwards (inclusive) and // before |delete_end|. You may use a null Time value to do an unbounded // delete in either direction. - bool RemoveLoginsCreatedBetween(const base::Time delete_begin, - const base::Time delete_end); + bool RemoveLoginsCreatedBetween(base::Time delete_begin, + base::Time delete_end); // Loads a list of matching password forms into the specified vector |forms|. // The list will contain all possibly relevant entries to the observed |form|, // including blacklisted matches. bool GetLogins(const webkit_glue::PasswordForm& form, - std::vector<webkit_glue::PasswordForm*>* forms) const; + std::vector<webkit_glue::PasswordForm*>* forms); // Loads the complete list of password forms into the specified vector |forms| // if include_blacklisted is true, otherwise only loads those which are // actually autofillable; i.e haven't been blacklisted by the user selecting // the 'Never for this site' button. bool GetAllLogins(std::vector<webkit_glue::PasswordForm*>* forms, - bool include_blacklisted) const; + bool include_blacklisted); ////////////////////////////////////////////////////////////////////////////// // @@ -143,20 +147,20 @@ class WebDatabase { bool GetFormValuesForElementName(const std::wstring& name, const std::wstring& prefix, std::vector<std::wstring>* values, - int limit) const; + int limit); // Removes rows from autofill_dates if they were created on or after // |delete_begin| and strictly before |delete_end|. Decrements the count of // the corresponding rows in the autofill table, and removes those rows if the // count goes to 0. - bool RemoveFormElementsAddedBetween(const base::Time delete_begin, - const base::Time delete_end); + bool RemoveFormElementsAddedBetween(base::Time delete_begin, + base::Time delete_end); // Removes from autofill_dates rows with given pair_id where date_created lies // between delte_begin and delte_end. bool RemoveFormElementForTimeRange(int64 pair_id, - const base::Time delete_begin, - const base::Time delete_end, + base::Time delete_begin, + base::Time delete_end, int* how_many); // Increments the count in the row corresponding to |pair_id| by |delta|. @@ -168,11 +172,10 @@ class WebDatabase { bool GetIDAndCountOfFormElement( const webkit_glue::AutofillForm::Element& element, int64* pair_id, - int* count) const; + int* count); // Gets the count only given the pair_id. - bool GetCountOfFormElement(int64 pair_id, - int* count) const; + bool GetCountOfFormElement(int64 pair_id, int* count); // Updates the count entry in the row corresponding to |pair_id| to |count|. bool SetCountOfFormElement(int64 pair_id, int count); @@ -184,7 +187,7 @@ class WebDatabase { int64* pair_id); // Adds a new row to the autofill_dates table. - bool InsertPairIDAndDate(int64 pair_id, const base::Time date_created); + bool InsertPairIDAndDate(int64 pair_id, base::Time date_created); // Removes row from the autofill tables given |pair_id|. bool RemoveFormElementForID(int64 pair_id); @@ -199,10 +202,10 @@ class WebDatabase { ////////////////////////////////////////////////////////////////////////////// bool SetWebAppImage(const GURL& url, const SkBitmap& image); - bool GetWebAppImages(const GURL& url, std::vector<SkBitmap>* images) const; + bool GetWebAppImages(const GURL& url, std::vector<SkBitmap>* images); bool SetWebAppHasAllImages(const GURL& url, bool has_all_images); - bool GetWebAppHasAllImages(const GURL& url) const; + bool GetWebAppHasAllImages(const GURL& url); bool RemoveWebApp(const GURL& url); @@ -224,11 +227,10 @@ class WebDatabase { void MigrateOldVersionsAsNeeded(); - sqlite3* db_; - int transaction_nesting_; - MetaTableHelper meta_table_; + sql::Connection db_; + sql::MetaTable meta_table_; DISALLOW_COPY_AND_ASSIGN(WebDatabase); }; -#endif // CHROME_BROWSER_WEBDATA_WEB_DATABASE_H__ +#endif // CHROME_BROWSER_WEBDATA_WEB_DATABASE_H_ diff --git a/chrome/browser/webdata/web_database_unittest.cc b/chrome/browser/webdata/web_database_unittest.cc index a2ac50d..68d56d8 100644 --- a/chrome/browser/webdata/web_database_unittest.cc +++ b/chrome/browser/webdata/web_database_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -87,7 +87,7 @@ class WebDatabaseTest : public testing::Test { TEST_F(WebDatabaseTest, Keywords) { WebDatabase db; - EXPECT_TRUE(db.Init(file_.ToWStringHack())); + EXPECT_TRUE(db.Init(file_)); TemplateURL template_url; template_url.set_short_name(L"short_name"); @@ -148,7 +148,7 @@ TEST_F(WebDatabaseTest, Keywords) { TEST_F(WebDatabaseTest, KeywordMisc) { WebDatabase db; - EXPECT_TRUE(db.Init(file_.ToWStringHack())); + EXPECT_TRUE(db.Init(file_)); ASSERT_EQ(0, db.GetDefaulSearchProviderID()); ASSERT_EQ(0, db.GetBuitinKeywordVersion()); @@ -163,7 +163,7 @@ TEST_F(WebDatabaseTest, KeywordMisc) { TEST_F(WebDatabaseTest, UpdateKeyword) { WebDatabase db; - EXPECT_TRUE(db.Init(file_.ToWStringHack())); + EXPECT_TRUE(db.Init(file_)); TemplateURL template_url; template_url.set_short_name(L"short_name"); @@ -225,7 +225,7 @@ TEST_F(WebDatabaseTest, UpdateKeyword) { TEST_F(WebDatabaseTest, KeywordWithNoFavicon) { WebDatabase db; - EXPECT_TRUE(db.Init(file_.ToWStringHack())); + EXPECT_TRUE(db.Init(file_)); TemplateURL template_url; template_url.set_short_name(L"short_name"); @@ -252,7 +252,7 @@ TEST_F(WebDatabaseTest, KeywordWithNoFavicon) { TEST_F(WebDatabaseTest, Logins) { WebDatabase db; - EXPECT_TRUE(db.Init(file_.ToWStringHack())); + EXPECT_TRUE(db.Init(file_)); std::vector<PasswordForm*> result; @@ -385,7 +385,7 @@ TEST_F(WebDatabaseTest, Logins) { TEST_F(WebDatabaseTest, Autofill) { WebDatabase db; - EXPECT_TRUE(db.Init(file_.ToWStringHack())); + EXPECT_TRUE(db.Init(file_)); Time t1 = Time::Now(); @@ -517,7 +517,7 @@ static void ClearResults(std::vector<PasswordForm*>* results) { TEST_F(WebDatabaseTest, ClearPrivateData_SavedPasswords) { WebDatabase db; - EXPECT_TRUE(db.Init(file_.ToWStringHack())); + EXPECT_TRUE(db.Init(file_)); std::vector<PasswordForm*> result; @@ -559,7 +559,7 @@ TEST_F(WebDatabaseTest, ClearPrivateData_SavedPasswords) { TEST_F(WebDatabaseTest, BlacklistedLogins) { WebDatabase db; - EXPECT_TRUE(db.Init(file_.ToWStringHack())); + EXPECT_TRUE(db.Init(file_)); std::vector<PasswordForm*> result; // Verify the database is empty. @@ -598,7 +598,7 @@ TEST_F(WebDatabaseTest, BlacklistedLogins) { TEST_F(WebDatabaseTest, WebAppHasAllImages) { WebDatabase db; - EXPECT_TRUE(db.Init(file_.ToWStringHack())); + EXPECT_TRUE(db.Init(file_)); GURL url("http://google.com/"); // Initial value for unknown web app should be false. @@ -616,7 +616,7 @@ TEST_F(WebDatabaseTest, WebAppHasAllImages) { TEST_F(WebDatabaseTest, WebAppImages) { WebDatabase db; - ASSERT_TRUE(db.Init(file_.ToWStringHack())); + ASSERT_TRUE(db.Init(file_)); GURL url("http://google.com/"); // Web app should initially have no images. diff --git a/chrome/browser/webdata/web_database_win.cc b/chrome/browser/webdata/web_database_win.cc index 4bfcc02..9ffbf9b 100644 --- a/chrome/browser/webdata/web_database_win.cc +++ b/chrome/browser/webdata/web_database_win.cc @@ -1,29 +1,30 @@ -// Copyright (c) 2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/webdata/web_database.h" +#include "app/sql/statement.h" #include "base/logging.h" +#include "base/string_util.h" #include "base/time.h" #include "chrome/browser/password_manager/ie7_password.h" -#include "chrome/common/sqlite_utils.h" bool WebDatabase::AddIE7Login(const IE7PasswordInfo& info) { - SQLStatement s; - if (s.prepare(db_, - "INSERT OR REPLACE INTO ie7_logins " - "(url_hash, password_value, date_created) " - "VALUES (?, ?, ?)") != SQLITE_OK) { - NOTREACHED() << "Statement prepare failed"; + sql::Statement s(db_.GetUniqueStatement( + "INSERT OR REPLACE INTO ie7_logins " + "(url_hash, password_value, date_created) " + "VALUES (?,?,?)")); + if (!s) { + NOTREACHED() << db_.GetErrorMessage(); return false; } - s.bind_wstring(0, info.url_hash); - s.bind_blob(1, &info.encrypted_data.front(), - static_cast<int>(info.encrypted_data.size())); - s.bind_int64(2, info.date_created.ToTimeT()); - if (s.step() != SQLITE_DONE) { + s.BindString(0, WideToUTF8(info.url_hash)); + s.BindBlob(1, &info.encrypted_data.front(), + static_cast<int>(info.encrypted_data.size())); + s.BindInt64(2, info.date_created.ToTimeT()); + if (!s.Run()) { NOTREACHED(); return false; } @@ -31,17 +32,16 @@ bool WebDatabase::AddIE7Login(const IE7PasswordInfo& info) { } bool WebDatabase::RemoveIE7Login(const IE7PasswordInfo& info) { - SQLStatement s; // Remove a login by UNIQUE-constrained fields. - if (s.prepare(db_, - "DELETE FROM ie7_logins WHERE " - "url_hash = ?") != SQLITE_OK) { - NOTREACHED() << "Statement prepare failed"; + sql::Statement s(db_.GetUniqueStatement( + "DELETE FROM ie7_logins WHERE url_hash = ?")); + if (!s) { + NOTREACHED() << db_.GetErrorMessage(); return false; } - s.bind_wstring(0, info.url_hash); + s.BindString(0, WideToUTF8(info.url_hash)); - if (s.step() != SQLITE_DONE) { + if (!s.Run()) { NOTREACHED(); return false; } @@ -51,22 +51,19 @@ bool WebDatabase::RemoveIE7Login(const IE7PasswordInfo& info) { bool WebDatabase::GetIE7Login(const IE7PasswordInfo& info, IE7PasswordInfo* result) { DCHECK(result); - SQLStatement s; - if (s.prepare(db_, - "SELECT password_value, date_created FROM ie7_logins " - "WHERE url_hash == ? ") != SQLITE_OK) { - NOTREACHED() << "Statement prepare failed"; + sql::Statement s(db_.GetUniqueStatement( + "SELECT password_value, date_created FROM ie7_logins " + "WHERE url_hash == ? ")); + if (!s) { + NOTREACHED() << db_.GetErrorMessage(); return false; } - s.bind_wstring(0, info.url_hash); - - int64 query_result = s.step(); - if (query_result == SQLITE_ROW) { - s.column_blob_as_vector(0, &result->encrypted_data); - result->date_created = base::Time::FromTimeT(s.column_int64(1)); + s.BindString(0, WideToUTF8(info.url_hash)); + if (s.Step()) { + s.ColumnBlobAsVector(0, &result->encrypted_data); + result->date_created = base::Time::FromTimeT(s.ColumnInt64(1)); result->url_hash = info.url_hash; - s.step(); } - return query_result == SQLITE_DONE; + return s.Succeeded(); } diff --git a/chrome/chrome.gyp b/chrome/chrome.gyp index bf939fb..51ea6ac 100644 --- a/chrome/chrome.gyp +++ b/chrome/chrome.gyp @@ -444,8 +444,6 @@ 'common/extensions/user_script.cc', 'common/extensions/user_script.h', 'common/gfx/utils.h', - 'common/net/cookie_monster_sqlite.cc', - 'common/net/cookie_monster_sqlite.h', 'common/net/dns.h', 'common/net/url_request_intercept_job.cc', 'common/net/url_request_intercept_job.h', @@ -1559,6 +1557,8 @@ 'browser/modal_html_dialog_delegate.h', 'browser/net/chrome_url_request_context.cc', 'browser/net/chrome_url_request_context.h', + 'browser/net/sqlite_persistent_cookie_store.cc', + 'browser/net/sqlite_persistent_cookie_store.h', 'browser/net/dns_global.cc', 'browser/net/dns_global.h', 'browser/net/dns_host_info.cc', |