This source file includes following definitions.
- InitTables
- GetRedirects
- SetRedirects
- RecordRecoveryEvent
- FixThumbnailsTable
- RecoverDatabaseOrRaze
- DatabaseErrorCallback
- Init
- InitImpl
- UpgradeToVersion3
- GetPageThumbnails
- SetPageThumbnail
- UpdatePageThumbnail
- AddPageThumbnail
- UpdatePageRank
- UpdatePageRankNoTransaction
- GetPageThumbnail
- GetURLRank
- RemoveURL
- CreateDB
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/browser/history/top_sites.h"
#include "chrome/browser/history/top_sites_database.h"
#include "chrome/common/thumbnail_score.h"
#include "sql/connection.h"
#include "sql/recovery.h"
#include "sql/statement.h"
#include "sql/transaction.h"
#include "third_party/sqlite/sqlite3.h"
namespace {
static const int kVersionNumber = 3;
static const int kDeprecatedVersionNumber = 1;
bool InitTables(sql::Connection* db) {
const char kThumbnailsSql[] =
"CREATE TABLE IF NOT EXISTS thumbnails ("
"url LONGVARCHAR PRIMARY KEY,"
"url_rank INTEGER,"
"title LONGVARCHAR,"
"thumbnail BLOB,"
"redirects LONGVARCHAR,"
"boring_score DOUBLE DEFAULT 1.0,"
"good_clipping INTEGER DEFAULT 0,"
"at_top INTEGER DEFAULT 0,"
"last_updated INTEGER DEFAULT 0,"
"load_completed INTEGER DEFAULT 0,"
"last_forced INTEGER DEFAULT 0)";
return db->Execute(kThumbnailsSql);
}
std::string GetRedirects(const history::MostVisitedURL& url) {
std::vector<std::string> redirects;
for (size_t i = 0; i < url.redirects.size(); i++)
redirects.push_back(url.redirects[i].spec());
return JoinString(redirects, ' ');
}
void SetRedirects(const std::string& redirects, history::MostVisitedURL* url) {
std::vector<std::string> redirects_vector;
base::SplitStringAlongWhitespace(redirects, &redirects_vector);
for (size_t i = 0; i < redirects_vector.size(); ++i)
url->redirects.push_back(GURL(redirects_vector[i]));
}
enum RecoveryEventType {
RECOVERY_EVENT_RECOVERED = 0,
RECOVERY_EVENT_DEPRECATED,
RECOVERY_EVENT_FAILED_SCOPER,
RECOVERY_EVENT_FAILED_META_VERSION,
RECOVERY_EVENT_FAILED_META_WRONG_VERSION,
RECOVERY_EVENT_FAILED_META_INIT,
RECOVERY_EVENT_FAILED_SCHEMA_INIT,
RECOVERY_EVENT_FAILED_AUTORECOVER_THUMBNAILS,
RECOVERY_EVENT_FAILED_COMMIT,
RECOVERY_EVENT_INVARIANT_RANK,
RECOVERY_EVENT_INVARIANT_REDIRECT,
RECOVERY_EVENT_INVARIANT_CONTIGUOUS,
RECOVERY_EVENT_MAX,
};
void RecordRecoveryEvent(RecoveryEventType recovery_event) {
UMA_HISTOGRAM_ENUMERATION("History.TopSitesRecovery",
recovery_event, RECOVERY_EVENT_MAX);
}
void FixThumbnailsTable(sql::Connection* db) {
const char kFixRankSql[] =
"DELETE FROM thumbnails "
"WHERE (url_rank = -1 AND last_forced = 0) "
"OR (url_rank <> -1 AND last_forced <> 0)";
ignore_result(db->Execute(kFixRankSql));
if (db->GetLastChangeCount() > 0)
RecordRecoveryEvent(RECOVERY_EVENT_INVARIANT_RANK);
const char kFixRedirectsSql[] =
"DELETE FROM thumbnails "
"WHERE url <> substr(redirects, -length(url), length(url))";
ignore_result(db->Execute(kFixRedirectsSql));
if (db->GetLastChangeCount() > 0)
RecordRecoveryEvent(RECOVERY_EVENT_INVARIANT_REDIRECT);
const char kByRankSql[] =
"SELECT url_rank, rowid FROM thumbnails WHERE url_rank <> -1 "
"ORDER BY url_rank";
sql::Statement select_statement(db->GetUniqueStatement(kByRankSql));
const char kAdjustRankSql[] =
"UPDATE thumbnails SET url_rank = ? WHERE rowid = ?";
sql::Statement update_statement(db->GetUniqueStatement(kAdjustRankSql));
int next_rank = 0;
bool adjusted = false;
while (select_statement.Step()) {
const int url_rank = select_statement.ColumnInt(0);
if (url_rank != next_rank) {
adjusted = true;
update_statement.Reset(true);
update_statement.BindInt(0, next_rank);
update_statement.BindInt64(1, select_statement.ColumnInt64(1));
update_statement.Run();
}
++next_rank;
}
if (adjusted)
RecordRecoveryEvent(RECOVERY_EVENT_INVARIANT_CONTIGUOUS);
}
void RecoverDatabaseOrRaze(sql::Connection* db, const base::FilePath& db_path) {
DCHECK_EQ(3, kVersionNumber);
db->reset_error_callback();
size_t thumbnails_recovered = 0;
int64 original_size = 0;
base::GetFileSize(db_path, &original_size);
scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(db, db_path);
if (!recovery) {
RecordRecoveryEvent(RECOVERY_EVENT_FAILED_SCOPER);
return;
}
int version = 0;
if (!recovery->SetupMeta() || !recovery->GetMetaVersionNumber(&version)) {
sql::Recovery::Rollback(recovery.Pass());
RecordRecoveryEvent(RECOVERY_EVENT_FAILED_META_VERSION);
return;
}
if (version <= kDeprecatedVersionNumber) {
sql::Recovery::Unrecoverable(recovery.Pass());
RecordRecoveryEvent(RECOVERY_EVENT_DEPRECATED);
return;
}
if (version != 2 && version != 3) {
RecordRecoveryEvent(RECOVERY_EVENT_FAILED_META_WRONG_VERSION);
sql::Recovery::Rollback(recovery.Pass());
return;
}
sql::MetaTable recover_meta_table;
if (!recover_meta_table.Init(recovery->db(), kVersionNumber,
kVersionNumber)) {
sql::Recovery::Rollback(recovery.Pass());
RecordRecoveryEvent(RECOVERY_EVENT_FAILED_META_INIT);
return;
}
if (!InitTables(recovery->db())) {
sql::Recovery::Rollback(recovery.Pass());
RecordRecoveryEvent(RECOVERY_EVENT_FAILED_SCHEMA_INIT);
return;
}
if (!recovery->AutoRecoverTable("thumbnails", 1, &thumbnails_recovered)) {
sql::Recovery::Rollback(recovery.Pass());
RecordRecoveryEvent(RECOVERY_EVENT_FAILED_AUTORECOVER_THUMBNAILS);
return;
}
FixThumbnailsTable(recovery->db());
if (!sql::Recovery::Recovered(recovery.Pass())) {
RecordRecoveryEvent(RECOVERY_EVENT_FAILED_COMMIT);
return;
}
int64 final_size = 0;
if (original_size > 0 &&
base::GetFileSize(db_path, &final_size) &&
final_size > 0) {
UMA_HISTOGRAM_PERCENTAGE("History.TopSitesRecoveredPercentage",
final_size * 100 / original_size);
}
UMA_HISTOGRAM_COUNTS_10000("History.TopSitesRecoveredRowsThumbnails",
thumbnails_recovered);
RecordRecoveryEvent(RECOVERY_EVENT_RECOVERED);
}
void DatabaseErrorCallback(sql::Connection* db,
const base::FilePath& db_path,
int extended_error,
sql::Statement* stmt) {
int error = (extended_error & 0xFF);
if (error == SQLITE_CORRUPT ||
error == SQLITE_CANTOPEN ||
error == SQLITE_NOTADB) {
RecoverDatabaseOrRaze(db, db_path);
}
if (!sql::Connection::ShouldIgnoreSqliteError(extended_error))
DLOG(FATAL) << db->GetErrorMessage();
}
}
namespace history {
const int TopSitesDatabase::kRankOfForcedURL = -1;
const int TopSitesDatabase::kRankOfNonExistingURL = -2;
TopSitesDatabase::TopSitesDatabase() {
}
TopSitesDatabase::~TopSitesDatabase() {
}
bool TopSitesDatabase::Init(const base::FilePath& db_name) {
const size_t kAttempts = 2;
for (size_t i = 0; i < kAttempts; ++i) {
if (InitImpl(db_name))
return true;
meta_table_.Reset();
db_.reset();
}
return false;
}
bool TopSitesDatabase::InitImpl(const base::FilePath& db_name) {
const bool file_existed = base::PathExists(db_name);
db_.reset(CreateDB(db_name));
if (!db_)
return false;
const bool does_meta_exist = sql::MetaTable::DoesTableExist(db_.get());
if (!does_meta_exist && file_existed) {
if (!db_->Raze())
return false;
}
DCHECK_LT(kDeprecatedVersionNumber, kVersionNumber);
sql::MetaTable::RazeIfDeprecated(db_.get(), kDeprecatedVersionNumber);
sql::Transaction transaction(db_.get());
if (!transaction.Begin())
return false;
if (!meta_table_.Init(db_.get(), kVersionNumber, kVersionNumber))
return false;
if (!InitTables(db_.get()))
return false;
if (meta_table_.GetVersionNumber() == 2) {
if (!UpgradeToVersion3()) {
LOG(WARNING) << "Unable to upgrade top sites database to version 3.";
return false;
}
}
if (meta_table_.GetVersionNumber() != kVersionNumber)
return false;
if (!transaction.Commit())
return false;
return true;
}
bool TopSitesDatabase::UpgradeToVersion3() {
if (!db_->Execute(
"ALTER TABLE thumbnails ADD last_forced INTEGER DEFAULT 0")) {
NOTREACHED();
return false;
}
meta_table_.SetVersionNumber(3);
return true;
}
void TopSitesDatabase::GetPageThumbnails(MostVisitedURLList* urls,
URLToImagesMap* thumbnails) {
sql::Statement statement(db_->GetCachedStatement(
SQL_FROM_HERE,
"SELECT url, url_rank, title, thumbnail, redirects, "
"boring_score, good_clipping, at_top, last_updated, load_completed, "
"last_forced FROM thumbnails ORDER BY url_rank, last_forced"));
if (!statement.is_valid()) {
LOG(WARNING) << db_->GetErrorMessage();
return;
}
urls->clear();
thumbnails->clear();
while (statement.Step()) {
MostVisitedURL url;
GURL gurl(statement.ColumnString(0));
url.url = gurl;
url.title = statement.ColumnString16(2);
url.last_forced_time =
base::Time::FromInternalValue(statement.ColumnInt64(10));
std::string redirects = statement.ColumnString(4);
SetRedirects(redirects, &url);
urls->push_back(url);
std::vector<unsigned char> data;
statement.ColumnBlobAsVector(3, &data);
Images thumbnail;
if (!data.empty())
thumbnail.thumbnail = base::RefCountedBytes::TakeVector(&data);
thumbnail.thumbnail_score.boring_score = statement.ColumnDouble(5);
thumbnail.thumbnail_score.good_clipping = statement.ColumnBool(6);
thumbnail.thumbnail_score.at_top = statement.ColumnBool(7);
thumbnail.thumbnail_score.time_at_snapshot =
base::Time::FromInternalValue(statement.ColumnInt64(8));
thumbnail.thumbnail_score.load_completed = statement.ColumnBool(9);
(*thumbnails)[gurl] = thumbnail;
}
}
void TopSitesDatabase::SetPageThumbnail(const MostVisitedURL& url,
int new_rank,
const Images& thumbnail) {
sql::Transaction transaction(db_.get());
transaction.Begin();
int rank = GetURLRank(url);
if (rank == kRankOfNonExistingURL) {
AddPageThumbnail(url, new_rank, thumbnail);
} else {
UpdatePageRankNoTransaction(url, new_rank);
UpdatePageThumbnail(url, thumbnail);
}
transaction.Commit();
}
bool TopSitesDatabase::UpdatePageThumbnail(
const MostVisitedURL& url, const Images& thumbnail) {
sql::Statement statement(db_->GetCachedStatement(
SQL_FROM_HERE,
"UPDATE thumbnails SET "
"title = ?, thumbnail = ?, redirects = ?, "
"boring_score = ?, good_clipping = ?, at_top = ?, last_updated = ?, "
"load_completed = ?, last_forced = ?"
"WHERE url = ? "));
statement.BindString16(0, url.title);
if (thumbnail.thumbnail.get() && thumbnail.thumbnail->front()) {
statement.BindBlob(1, thumbnail.thumbnail->front(),
static_cast<int>(thumbnail.thumbnail->size()));
}
statement.BindString(2, GetRedirects(url));
const ThumbnailScore& score = thumbnail.thumbnail_score;
statement.BindDouble(3, score.boring_score);
statement.BindBool(4, score.good_clipping);
statement.BindBool(5, score.at_top);
statement.BindInt64(6, score.time_at_snapshot.ToInternalValue());
statement.BindBool(7, score.load_completed);
statement.BindInt64(8, url.last_forced_time.ToInternalValue());
statement.BindString(9, url.url.spec());
return statement.Run();
}
void TopSitesDatabase::AddPageThumbnail(const MostVisitedURL& url,
int new_rank,
const Images& thumbnail) {
sql::Statement statement(db_->GetCachedStatement(
SQL_FROM_HERE,
"INSERT OR REPLACE INTO thumbnails "
"(url, url_rank, title, thumbnail, redirects, "
"boring_score, good_clipping, at_top, last_updated, load_completed, "
"last_forced) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"));
statement.BindString(0, url.url.spec());
statement.BindInt(1, kRankOfForcedURL);
statement.BindString16(2, url.title);
if (thumbnail.thumbnail.get() && thumbnail.thumbnail->front()) {
statement.BindBlob(3, thumbnail.thumbnail->front(),
static_cast<int>(thumbnail.thumbnail->size()));
}
statement.BindString(4, GetRedirects(url));
const ThumbnailScore& score = thumbnail.thumbnail_score;
statement.BindDouble(5, score.boring_score);
statement.BindBool(6, score.good_clipping);
statement.BindBool(7, score.at_top);
statement.BindInt64(8, score.time_at_snapshot.ToInternalValue());
statement.BindBool(9, score.load_completed);
int64 last_forced = url.last_forced_time.ToInternalValue();
DCHECK((last_forced == 0) == (new_rank != kRankOfForcedURL))
<< "Thumbnail without a forced time stamp has a forced rank, or the "
<< "opposite.";
statement.BindInt64(10, last_forced);
if (!statement.Run())
return;
if (new_rank != kRankOfForcedURL)
UpdatePageRankNoTransaction(url, new_rank);
}
void TopSitesDatabase::UpdatePageRank(const MostVisitedURL& url,
int new_rank) {
DCHECK((url.last_forced_time.ToInternalValue() == 0) ==
(new_rank != kRankOfForcedURL))
<< "Thumbnail without a forced time stamp has a forced rank, or the "
<< "opposite.";
sql::Transaction transaction(db_.get());
transaction.Begin();
UpdatePageRankNoTransaction(url, new_rank);
transaction.Commit();
}
void TopSitesDatabase::UpdatePageRankNoTransaction(
const MostVisitedURL& url, int new_rank) {
DCHECK_GT(db_->transaction_nesting(), 0);
DCHECK((url.last_forced_time.is_null()) == (new_rank != kRankOfForcedURL))
<< "Thumbnail without a forced time stamp has a forced rank, or the "
<< "opposite.";
int prev_rank = GetURLRank(url);
if (prev_rank == kRankOfNonExistingURL) {
LOG(WARNING) << "Updating rank of an unknown URL: " << url.url.spec();
return;
}
if (prev_rank > new_rank) {
if (new_rank == kRankOfForcedURL) {
sql::Statement shift_statement(db_->GetCachedStatement(
SQL_FROM_HERE,
"UPDATE thumbnails "
"SET url_rank = url_rank - 1 "
"WHERE url_rank > ?"));
shift_statement.BindInt(0, prev_rank);
shift_statement.Run();
} else {
sql::Statement shift_statement(db_->GetCachedStatement(
SQL_FROM_HERE,
"UPDATE thumbnails "
"SET url_rank = url_rank + 1 "
"WHERE url_rank >= ? AND url_rank < ?"));
shift_statement.BindInt(0, new_rank);
shift_statement.BindInt(1, prev_rank);
shift_statement.Run();
}
} else if (prev_rank < new_rank) {
if (prev_rank == kRankOfForcedURL) {
sql::Statement shift_statement(db_->GetCachedStatement(
SQL_FROM_HERE,
"UPDATE thumbnails "
"SET url_rank = url_rank + 1 "
"WHERE url_rank >= ?"));
shift_statement.BindInt(0, new_rank);
shift_statement.Run();
} else {
sql::Statement shift_statement(db_->GetCachedStatement(
SQL_FROM_HERE,
"UPDATE thumbnails "
"SET url_rank = url_rank - 1 "
"WHERE url_rank > ? AND url_rank <= ?"));
shift_statement.BindInt(0, prev_rank);
shift_statement.BindInt(1, new_rank);
shift_statement.Run();
}
}
sql::Statement set_statement(db_->GetCachedStatement(
SQL_FROM_HERE,
"UPDATE thumbnails "
"SET url_rank = ?, last_forced = ? "
"WHERE url == ?"));
set_statement.BindInt(0, new_rank);
set_statement.BindInt64(1, url.last_forced_time.ToInternalValue());
set_statement.BindString(2, url.url.spec());
set_statement.Run();
}
bool TopSitesDatabase::GetPageThumbnail(const GURL& url,
Images* thumbnail) {
sql::Statement statement(db_->GetCachedStatement(
SQL_FROM_HERE,
"SELECT thumbnail, boring_score, good_clipping, at_top, last_updated "
"FROM thumbnails WHERE url=?"));
statement.BindString(0, url.spec());
if (!statement.Step())
return false;
std::vector<unsigned char> data;
statement.ColumnBlobAsVector(0, &data);
thumbnail->thumbnail = base::RefCountedBytes::TakeVector(&data);
thumbnail->thumbnail_score.boring_score = statement.ColumnDouble(1);
thumbnail->thumbnail_score.good_clipping = statement.ColumnBool(2);
thumbnail->thumbnail_score.at_top = statement.ColumnBool(3);
thumbnail->thumbnail_score.time_at_snapshot =
base::Time::FromInternalValue(statement.ColumnInt64(4));
return true;
}
int TopSitesDatabase::GetURLRank(const MostVisitedURL& url) {
sql::Statement select_statement(db_->GetCachedStatement(
SQL_FROM_HERE,
"SELECT url_rank "
"FROM thumbnails WHERE url=?"));
select_statement.BindString(0, url.url.spec());
if (select_statement.Step())
return select_statement.ColumnInt(0);
return kRankOfNonExistingURL;
}
bool TopSitesDatabase::RemoveURL(const MostVisitedURL& url) {
int old_rank = GetURLRank(url);
if (old_rank == kRankOfNonExistingURL)
return false;
sql::Transaction transaction(db_.get());
transaction.Begin();
if (old_rank != kRankOfForcedURL) {
sql::Statement shift_statement(db_->GetCachedStatement(
SQL_FROM_HERE,
"UPDATE thumbnails "
"SET url_rank = url_rank - 1 "
"WHERE url_rank > ?"));
shift_statement.BindInt(0, old_rank);
if (!shift_statement.Run())
return false;
}
sql::Statement delete_statement(
db_->GetCachedStatement(SQL_FROM_HERE,
"DELETE FROM thumbnails WHERE url = ?"));
delete_statement.BindString(0, url.url.spec());
if (!delete_statement.Run())
return false;
return transaction.Commit();
}
sql::Connection* TopSitesDatabase::CreateDB(const base::FilePath& db_name) {
scoped_ptr<sql::Connection> db(new sql::Connection());
db->set_histogram_tag("TopSites");
db->set_error_callback(base::Bind(&DatabaseErrorCallback,
db.get(), db_name));
db->set_page_size(4096);
db->set_cache_size(32);
if (!db->Open(db_name))
return NULL;
return db.release();
}
}