1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/history/top_sites_database.h"
7 #include "base/file_util.h"
8 #include "base/memory/ref_counted.h"
9 #include "base/metrics/histogram.h"
10 #include "base/strings/string_split.h"
11 #include "base/strings/string_util.h"
12 #include "chrome/browser/history/history_types.h"
13 #include "chrome/browser/history/top_sites.h"
14 #include "chrome/common/thumbnail_score.h"
15 #include "sql/connection.h"
16 #include "sql/recovery.h"
17 #include "sql/statement.h"
18 #include "sql/transaction.h"
19 #include "third_party/sqlite/sqlite3.h"
21 // Description of database table:
24 // url URL of the sites for which we have a thumbnail.
25 // url_rank Index of the URL in that thumbnail, 0-based. The thumbnail
26 // with the highest rank will be the next one evicted. Forced
27 // thumbnails have a rank of -1.
28 // title The title to display under that thumbnail.
29 // redirects A space separated list of URLs that are known to redirect
31 // boring_score How "boring" that thumbnail is. See ThumbnailScore.
32 // good_clipping True if the thumbnail was clipped from the bottom, keeping
33 // the entire width of the window. See ThumbnailScore.
34 // at_top True if the thumbnail was captured at the top of the
36 // last_updated The time at which this thumbnail was last updated.
37 // load_completed True if the thumbnail was captured after the page load was
39 // last_forced If this is a forced thumbnail, records the last time it
40 // was forced. If it's not a forced thumbnail, 0.
44 // For this database, schema migrations are deprecated after two
45 // years. This means that the oldest non-deprecated version should be
46 // two years old or greater (thus the migrations to get there are
47 // older). Databases containing deprecated versions will be cleared
48 // at startup. Since this database is a cache, losing old data is not
49 // fatal (in fact, very old data may be expired immediately at startup
52 // Version 3: b6d6a783/r231648 by beaudoin@chromium.org on 2013-10-29
53 // Version 2: eb0b24e6/r87284 by satorux@chromium.org on 2011-05-31
54 // Version 1: 809cc4d8/r64072 by sky@chromium.org on 2010-10-27 (deprecated)
56 // NOTE(shess): When changing the version, add a new golden file for
57 // the new version and a test to verify that Init() works with it.
58 // NOTE(shess): RecoverDatabaseOrRaze() depends on the specific
59 // version number. The code is subtle and in development, contact me
60 // if the necessary changes are not obvious.
61 static const int kVersionNumber = 3;
62 static const int kDeprecatedVersionNumber = 1; // and earlier.
64 bool InitTables(sql::Connection* db) {
65 const char kThumbnailsSql[] =
66 "CREATE TABLE IF NOT EXISTS thumbnails ("
67 "url LONGVARCHAR PRIMARY KEY,"
71 "redirects LONGVARCHAR,"
72 "boring_score DOUBLE DEFAULT 1.0,"
73 "good_clipping INTEGER DEFAULT 0,"
74 "at_top INTEGER DEFAULT 0,"
75 "last_updated INTEGER DEFAULT 0,"
76 "load_completed INTEGER DEFAULT 0,"
77 "last_forced INTEGER DEFAULT 0)";
78 return db->Execute(kThumbnailsSql);
81 // Encodes redirects into a string.
82 std::string GetRedirects(const history::MostVisitedURL& url) {
83 std::vector<std::string> redirects;
84 for (size_t i = 0; i < url.redirects.size(); i++)
85 redirects.push_back(url.redirects[i].spec());
86 return JoinString(redirects, ' ');
89 // Decodes redirects from a string and sets them for the url.
90 void SetRedirects(const std::string& redirects, history::MostVisitedURL* url) {
91 std::vector<std::string> redirects_vector;
92 base::SplitStringAlongWhitespace(redirects, &redirects_vector);
93 for (size_t i = 0; i < redirects_vector.size(); ++i)
94 url->redirects.push_back(GURL(redirects_vector[i]));
97 // Track various failure (and success) cases in recovery code.
99 // TODO(shess): The recovery code is complete, but by nature runs in challenging
100 // circumstances, so initially the default error response is to leave the
101 // existing database in place. This histogram is intended to expose the
102 // failures seen in the fleet. Frequent failure cases can be explored more
103 // deeply to see if the complexity to fix them is warranted. Infrequent failure
104 // cases can be resolved by marking the database unrecoverable (which will
107 // Based on the thumbnail_database.cc recovery code, FAILED_SCOPER should
108 // dominate, followed distantly by FAILED_META, with few or no other failures.
109 enum RecoveryEventType {
110 // Database successfully recovered.
111 RECOVERY_EVENT_RECOVERED = 0,
113 // Database successfully deprecated.
114 RECOVERY_EVENT_DEPRECATED,
116 // Sqlite.RecoveryEvent can usually be used to get more detail about the
117 // specific failure (see sql/recovery.cc).
118 RECOVERY_EVENT_FAILED_SCOPER,
119 RECOVERY_EVENT_FAILED_META_VERSION,
120 RECOVERY_EVENT_FAILED_META_WRONG_VERSION,
121 RECOVERY_EVENT_FAILED_META_INIT,
122 RECOVERY_EVENT_FAILED_SCHEMA_INIT,
123 RECOVERY_EVENT_FAILED_AUTORECOVER_THUMBNAILS,
124 RECOVERY_EVENT_FAILED_COMMIT,
126 // Track invariants resolved by FixThumbnailsTable().
127 RECOVERY_EVENT_INVARIANT_RANK,
128 RECOVERY_EVENT_INVARIANT_REDIRECT,
129 RECOVERY_EVENT_INVARIANT_CONTIGUOUS,
131 // Always keep this at the end.
135 void RecordRecoveryEvent(RecoveryEventType recovery_event) {
136 UMA_HISTOGRAM_ENUMERATION("History.TopSitesRecovery",
137 recovery_event, RECOVERY_EVENT_MAX);
140 // Most corruption comes down to atomic updates between pages being broken
141 // somehow. This can result in either missing data, or overlapping data,
142 // depending on the operation broken. This table has large rows, which will use
143 // overflow pages, so it is possible (though unlikely) that a chain could fit
144 // together and yield a row with errors.
145 void FixThumbnailsTable(sql::Connection* db) {
146 // Enforce invariant separating forced and non-forced thumbnails.
147 const char kFixRankSql[] =
148 "DELETE FROM thumbnails "
149 "WHERE (url_rank = -1 AND last_forced = 0) "
150 "OR (url_rank <> -1 AND last_forced <> 0)";
151 ignore_result(db->Execute(kFixRankSql));
152 if (db->GetLastChangeCount() > 0)
153 RecordRecoveryEvent(RECOVERY_EVENT_INVARIANT_RANK);
155 // Enforce invariant that url is in its own redirects.
156 const char kFixRedirectsSql[] =
157 "DELETE FROM thumbnails "
158 "WHERE url <> substr(redirects, -length(url), length(url))";
159 ignore_result(db->Execute(kFixRedirectsSql));
160 if (db->GetLastChangeCount() > 0)
161 RecordRecoveryEvent(RECOVERY_EVENT_INVARIANT_REDIRECT);
163 // Enforce invariant that url_rank>=0 forms a contiguous series.
164 // TODO(shess): I have not found an UPDATE+SUBSELECT method of managing this.
165 // It can be done with a temporary table and a subselect, but doing it
166 // manually is easier to follow. Another option would be to somehow integrate
167 // the renumbering into the table recovery code.
168 const char kByRankSql[] =
169 "SELECT url_rank, rowid FROM thumbnails WHERE url_rank <> -1 "
171 sql::Statement select_statement(db->GetUniqueStatement(kByRankSql));
173 const char kAdjustRankSql[] =
174 "UPDATE thumbnails SET url_rank = ? WHERE rowid = ?";
175 sql::Statement update_statement(db->GetUniqueStatement(kAdjustRankSql));
177 // Update any rows where |next_rank| doesn't match |url_rank|.
179 bool adjusted = false;
180 while (select_statement.Step()) {
181 const int url_rank = select_statement.ColumnInt(0);
182 if (url_rank != next_rank) {
184 update_statement.Reset(true);
185 update_statement.BindInt(0, next_rank);
186 update_statement.BindInt64(1, select_statement.ColumnInt64(1));
187 update_statement.Run();
192 RecordRecoveryEvent(RECOVERY_EVENT_INVARIANT_CONTIGUOUS);
195 // Recover the database to the extent possible, razing it if recovery is not
197 void RecoverDatabaseOrRaze(sql::Connection* db, const base::FilePath& db_path) {
198 // NOTE(shess): If the version changes, review this code.
199 DCHECK_EQ(3, kVersionNumber);
201 // It is almost certain that some operation against |db| will fail, prevent
203 db->reset_error_callback();
205 // For generating histogram stats.
206 size_t thumbnails_recovered = 0;
207 int64 original_size = 0;
208 base::GetFileSize(db_path, &original_size);
210 scoped_ptr<sql::Recovery> recovery = sql::Recovery::Begin(db, db_path);
212 RecordRecoveryEvent(RECOVERY_EVENT_FAILED_SCOPER);
216 // Setup the meta recovery table and fetch the version number from the corrupt
219 if (!recovery->SetupMeta() || !recovery->GetMetaVersionNumber(&version)) {
220 // TODO(shess): Prior histograms indicate all failures are in creating the
221 // recover virtual table for corrupt.meta. The table may not exist, or the
222 // database may be too far gone. Either way, unclear how to resolve.
223 sql::Recovery::Rollback(recovery.Pass());
224 RecordRecoveryEvent(RECOVERY_EVENT_FAILED_META_VERSION);
228 // This code runs in a context which may be able to read version information
229 // that the regular deprecation path cannot. The effect of this code will be
230 // to raze the database.
231 if (version <= kDeprecatedVersionNumber) {
232 sql::Recovery::Unrecoverable(recovery.Pass());
233 RecordRecoveryEvent(RECOVERY_EVENT_DEPRECATED);
237 // TODO(shess): Earlier versions have been deprecated, later versions should
238 // be impossible. Unrecoverable() seems like a feasible response if this is
239 // infrequent enough.
240 if (version != 2 && version != 3) {
241 RecordRecoveryEvent(RECOVERY_EVENT_FAILED_META_WRONG_VERSION);
242 sql::Recovery::Rollback(recovery.Pass());
246 // Both v2 and v3 recover to current schema version.
247 sql::MetaTable recover_meta_table;
248 if (!recover_meta_table.Init(recovery->db(), kVersionNumber,
250 sql::Recovery::Rollback(recovery.Pass());
251 RecordRecoveryEvent(RECOVERY_EVENT_FAILED_META_INIT);
255 // Create a fresh version of the schema. The recovery code uses
256 // conflict-resolution to handle duplicates, so any indices are necessary.
257 if (!InitTables(recovery->db())) {
258 // TODO(shess): Unable to create the new schema in the new database. The
259 // new database should be a temporary file, so being unable to work with it
260 // is pretty unclear.
262 // What are the potential responses, even? The recovery database could be
263 // opened as in-memory. If the temp database had a filesystem problem and
264 // the temp filesystem differs from the main database, then that could fix
266 sql::Recovery::Rollback(recovery.Pass());
267 RecordRecoveryEvent(RECOVERY_EVENT_FAILED_SCHEMA_INIT);
271 // The |1| is because v2 [thumbnails] has one less column than v3 did. In the
272 // v2 case the column will get default values.
273 if (!recovery->AutoRecoverTable("thumbnails", 1, &thumbnails_recovered)) {
274 sql::Recovery::Rollback(recovery.Pass());
275 RecordRecoveryEvent(RECOVERY_EVENT_FAILED_AUTORECOVER_THUMBNAILS);
279 // TODO(shess): Inline this?
280 FixThumbnailsTable(recovery->db());
282 if (!sql::Recovery::Recovered(recovery.Pass())) {
283 // TODO(shess): Very unclear what this failure would actually mean, and what
284 // should be done. Add histograms to Recovered() implementation to get some
286 RecordRecoveryEvent(RECOVERY_EVENT_FAILED_COMMIT);
290 // Track the size of the recovered database relative to the size of the input
291 // database. The size should almost always be smaller, unless the input
292 // database was empty to start with. If the percentage results are very low,
293 // something is awry.
294 int64 final_size = 0;
295 if (original_size > 0 &&
296 base::GetFileSize(db_path, &final_size) &&
298 UMA_HISTOGRAM_PERCENTAGE("History.TopSitesRecoveredPercentage",
299 final_size * 100 / original_size);
302 // Using 10,000 because these cases mostly care about "none recovered" and
303 // "lots recovered". More than 10,000 rows recovered probably means there's
304 // something wrong with the profile.
305 UMA_HISTOGRAM_COUNTS_10000("History.TopSitesRecoveredRowsThumbnails",
306 thumbnails_recovered);
308 RecordRecoveryEvent(RECOVERY_EVENT_RECOVERED);
311 void DatabaseErrorCallback(sql::Connection* db,
312 const base::FilePath& db_path,
314 sql::Statement* stmt) {
315 // TODO(shess): Assert that this is running on a safe thread. AFAICT, should
316 // be the history thread, but at this level I can't see how to reach that.
318 // Attempt to recover corrupt databases.
319 int error = (extended_error & 0xFF);
320 if (error == SQLITE_CORRUPT ||
321 error == SQLITE_CANTOPEN ||
322 error == SQLITE_NOTADB) {
323 RecoverDatabaseOrRaze(db, db_path);
326 // TODO(shess): This database's error histograms look like:
327 // 84% SQLITE_CORRUPT, SQLITE_CANTOPEN, SQLITE_NOTADB
329 // 6% SQLITE_IOERR variants
330 // 2% SQLITE_READONLY
332 // nominal SQLITE_TOBIG, SQLITE_AUTH, and SQLITE_BUSY. In the case of
333 // thumbnail_database.cc, as soon as the recovery code landed, SQLITE_IOERR
334 // shot to leadership. If the I/O error is system-level, there is probably no
335 // hope, but if it is restricted to something about the database file, it is
336 // possible that the recovery code could be brought to bear. In fact, it is
337 // possible that running recovery would be a reasonable default when errors
340 // The default handling is to assert on debug and to ignore on release.
341 if (!sql::Connection::ShouldIgnoreSqliteError(extended_error))
342 DLOG(FATAL) << db->GetErrorMessage();
350 const int TopSitesDatabase::kRankOfForcedURL = -1;
353 const int TopSitesDatabase::kRankOfNonExistingURL = -2;
355 TopSitesDatabase::TopSitesDatabase() {
358 TopSitesDatabase::~TopSitesDatabase() {
361 bool TopSitesDatabase::Init(const base::FilePath& db_name) {
362 // Retry failed InitImpl() in case the recovery system fixed things.
363 // TODO(shess): Instrument to figure out if there are any persistent failure
364 // cases which do not resolve themselves.
365 const size_t kAttempts = 2;
367 for (size_t i = 0; i < kAttempts; ++i) {
368 if (InitImpl(db_name))
377 bool TopSitesDatabase::InitImpl(const base::FilePath& db_name) {
378 const bool file_existed = base::PathExists(db_name);
380 db_.reset(CreateDB(db_name));
384 // An older version had data with no meta table. Deprecate by razing.
385 // TODO(shess): Just have RazeIfDeprecated() handle this case.
386 const bool does_meta_exist = sql::MetaTable::DoesTableExist(db_.get());
387 if (!does_meta_exist && file_existed) {
392 // Clear databases which are too old to process.
393 DCHECK_LT(kDeprecatedVersionNumber, kVersionNumber);
394 sql::MetaTable::RazeIfDeprecated(db_.get(), kDeprecatedVersionNumber);
396 // Scope initialization in a transaction so we can't be partially
398 sql::Transaction transaction(db_.get());
399 // TODO(shess): Failure to open transaction is bad, address it.
400 if (!transaction.Begin())
403 if (!meta_table_.Init(db_.get(), kVersionNumber, kVersionNumber))
406 if (!InitTables(db_.get()))
409 if (meta_table_.GetVersionNumber() == 2) {
410 if (!UpgradeToVersion3()) {
411 LOG(WARNING) << "Unable to upgrade top sites database to version 3.";
417 if (meta_table_.GetVersionNumber() != kVersionNumber)
420 // Initialization is complete.
421 if (!transaction.Commit())
427 bool TopSitesDatabase::UpgradeToVersion3() {
428 // Add 'last_forced' column.
430 "ALTER TABLE thumbnails ADD last_forced INTEGER DEFAULT 0")) {
434 meta_table_.SetVersionNumber(3);
438 void TopSitesDatabase::GetPageThumbnails(MostVisitedURLList* urls,
439 URLToImagesMap* thumbnails) {
440 sql::Statement statement(db_->GetCachedStatement(
442 "SELECT url, url_rank, title, thumbnail, redirects, "
443 "boring_score, good_clipping, at_top, last_updated, load_completed, "
444 "last_forced FROM thumbnails ORDER BY url_rank, last_forced"));
446 if (!statement.is_valid()) {
447 LOG(WARNING) << db_->GetErrorMessage();
454 while (statement.Step()) {
455 // Results are sorted by url_rank. For forced thumbnails with url_rank = -1,
456 // thumbnails are sorted by last_forced.
458 GURL gurl(statement.ColumnString(0));
460 url.title = statement.ColumnString16(2);
461 url.last_forced_time =
462 base::Time::FromInternalValue(statement.ColumnInt64(10));
463 std::string redirects = statement.ColumnString(4);
464 SetRedirects(redirects, &url);
465 urls->push_back(url);
467 std::vector<unsigned char> data;
468 statement.ColumnBlobAsVector(3, &data);
471 thumbnail.thumbnail = base::RefCountedBytes::TakeVector(&data);
472 thumbnail.thumbnail_score.boring_score = statement.ColumnDouble(5);
473 thumbnail.thumbnail_score.good_clipping = statement.ColumnBool(6);
474 thumbnail.thumbnail_score.at_top = statement.ColumnBool(7);
475 thumbnail.thumbnail_score.time_at_snapshot =
476 base::Time::FromInternalValue(statement.ColumnInt64(8));
477 thumbnail.thumbnail_score.load_completed = statement.ColumnBool(9);
478 (*thumbnails)[gurl] = thumbnail;
482 void TopSitesDatabase::SetPageThumbnail(const MostVisitedURL& url,
484 const Images& thumbnail) {
485 sql::Transaction transaction(db_.get());
488 int rank = GetURLRank(url);
489 if (rank == kRankOfNonExistingURL) {
490 AddPageThumbnail(url, new_rank, thumbnail);
492 UpdatePageRankNoTransaction(url, new_rank);
493 UpdatePageThumbnail(url, thumbnail);
496 transaction.Commit();
499 bool TopSitesDatabase::UpdatePageThumbnail(
500 const MostVisitedURL& url, const Images& thumbnail) {
501 sql::Statement statement(db_->GetCachedStatement(
503 "UPDATE thumbnails SET "
504 "title = ?, thumbnail = ?, redirects = ?, "
505 "boring_score = ?, good_clipping = ?, at_top = ?, last_updated = ?, "
506 "load_completed = ?, last_forced = ?"
508 statement.BindString16(0, url.title);
509 if (thumbnail.thumbnail.get() && thumbnail.thumbnail->front()) {
510 statement.BindBlob(1, thumbnail.thumbnail->front(),
511 static_cast<int>(thumbnail.thumbnail->size()));
513 statement.BindString(2, GetRedirects(url));
514 const ThumbnailScore& score = thumbnail.thumbnail_score;
515 statement.BindDouble(3, score.boring_score);
516 statement.BindBool(4, score.good_clipping);
517 statement.BindBool(5, score.at_top);
518 statement.BindInt64(6, score.time_at_snapshot.ToInternalValue());
519 statement.BindBool(7, score.load_completed);
520 statement.BindInt64(8, url.last_forced_time.ToInternalValue());
521 statement.BindString(9, url.url.spec());
523 return statement.Run();
526 void TopSitesDatabase::AddPageThumbnail(const MostVisitedURL& url,
528 const Images& thumbnail) {
529 sql::Statement statement(db_->GetCachedStatement(
531 "INSERT OR REPLACE INTO thumbnails "
532 "(url, url_rank, title, thumbnail, redirects, "
533 "boring_score, good_clipping, at_top, last_updated, load_completed, "
534 "last_forced) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"));
535 statement.BindString(0, url.url.spec());
536 statement.BindInt(1, kRankOfForcedURL); // Fist make it a forced thumbnail.
537 statement.BindString16(2, url.title);
538 if (thumbnail.thumbnail.get() && thumbnail.thumbnail->front()) {
539 statement.BindBlob(3, thumbnail.thumbnail->front(),
540 static_cast<int>(thumbnail.thumbnail->size()));
542 statement.BindString(4, GetRedirects(url));
543 const ThumbnailScore& score = thumbnail.thumbnail_score;
544 statement.BindDouble(5, score.boring_score);
545 statement.BindBool(6, score.good_clipping);
546 statement.BindBool(7, score.at_top);
547 statement.BindInt64(8, score.time_at_snapshot.ToInternalValue());
548 statement.BindBool(9, score.load_completed);
549 int64 last_forced = url.last_forced_time.ToInternalValue();
550 DCHECK((last_forced == 0) == (new_rank != kRankOfForcedURL))
551 << "Thumbnail without a forced time stamp has a forced rank, or the "
553 statement.BindInt64(10, last_forced);
554 if (!statement.Run())
557 // Update rank if this is not a forced thumbnail.
558 if (new_rank != kRankOfForcedURL)
559 UpdatePageRankNoTransaction(url, new_rank);
562 void TopSitesDatabase::UpdatePageRank(const MostVisitedURL& url,
564 DCHECK((url.last_forced_time.ToInternalValue() == 0) ==
565 (new_rank != kRankOfForcedURL))
566 << "Thumbnail without a forced time stamp has a forced rank, or the "
568 sql::Transaction transaction(db_.get());
570 UpdatePageRankNoTransaction(url, new_rank);
571 transaction.Commit();
574 // Caller should have a transaction open.
575 void TopSitesDatabase::UpdatePageRankNoTransaction(
576 const MostVisitedURL& url, int new_rank) {
577 DCHECK_GT(db_->transaction_nesting(), 0);
578 DCHECK((url.last_forced_time.is_null()) == (new_rank != kRankOfForcedURL))
579 << "Thumbnail without a forced time stamp has a forced rank, or the "
582 int prev_rank = GetURLRank(url);
583 if (prev_rank == kRankOfNonExistingURL) {
584 LOG(WARNING) << "Updating rank of an unknown URL: " << url.url.spec();
589 if (prev_rank > new_rank) {
590 if (new_rank == kRankOfForcedURL) {
591 // From non-forced to forced, shift down.
593 // -1, -1, -1, 0, 1, [2 -> -1], [3 -> 2], [4 -> 3]
594 sql::Statement shift_statement(db_->GetCachedStatement(
597 "SET url_rank = url_rank - 1 "
598 "WHERE url_rank > ?"));
599 shift_statement.BindInt(0, prev_rank);
600 shift_statement.Run();
602 // From non-forced to non-forced, shift up.
604 // -1, -1, -1, 0, [1 -> 2], [2 -> 3], [3 -> 1], 4
605 sql::Statement shift_statement(db_->GetCachedStatement(
608 "SET url_rank = url_rank + 1 "
609 "WHERE url_rank >= ? AND url_rank < ?"));
610 shift_statement.BindInt(0, new_rank);
611 shift_statement.BindInt(1, prev_rank);
612 shift_statement.Run();
614 } else if (prev_rank < new_rank) {
615 if (prev_rank == kRankOfForcedURL) {
616 // From non-forced to forced, shift up.
618 // -1, [-1 -> 2], -1, 0, 1, [2 -> 3], [3 -> 4], [4 -> 5]
619 sql::Statement shift_statement(db_->GetCachedStatement(
622 "SET url_rank = url_rank + 1 "
623 "WHERE url_rank >= ?"));
624 shift_statement.BindInt(0, new_rank);
625 shift_statement.Run();
627 // From non-forced to non-forced, shift down.
629 // -1, -1, -1, 0, [1 -> 3], [2 -> 1], [3 -> 2], 4
630 sql::Statement shift_statement(db_->GetCachedStatement(
633 "SET url_rank = url_rank - 1 "
634 "WHERE url_rank > ? AND url_rank <= ?"));
635 shift_statement.BindInt(0, prev_rank);
636 shift_statement.BindInt(1, new_rank);
637 shift_statement.Run();
641 // Set the url's rank and last_forced, since the latter changes when a URL
642 // goes from forced to non-forced and vice-versa.
643 sql::Statement set_statement(db_->GetCachedStatement(
646 "SET url_rank = ?, last_forced = ? "
648 set_statement.BindInt(0, new_rank);
649 set_statement.BindInt64(1, url.last_forced_time.ToInternalValue());
650 set_statement.BindString(2, url.url.spec());
654 bool TopSitesDatabase::GetPageThumbnail(const GURL& url,
656 sql::Statement statement(db_->GetCachedStatement(
658 "SELECT thumbnail, boring_score, good_clipping, at_top, last_updated "
659 "FROM thumbnails WHERE url=?"));
660 statement.BindString(0, url.spec());
661 if (!statement.Step())
664 std::vector<unsigned char> data;
665 statement.ColumnBlobAsVector(0, &data);
666 thumbnail->thumbnail = base::RefCountedBytes::TakeVector(&data);
667 thumbnail->thumbnail_score.boring_score = statement.ColumnDouble(1);
668 thumbnail->thumbnail_score.good_clipping = statement.ColumnBool(2);
669 thumbnail->thumbnail_score.at_top = statement.ColumnBool(3);
670 thumbnail->thumbnail_score.time_at_snapshot =
671 base::Time::FromInternalValue(statement.ColumnInt64(4));
675 int TopSitesDatabase::GetURLRank(const MostVisitedURL& url) {
676 sql::Statement select_statement(db_->GetCachedStatement(
679 "FROM thumbnails WHERE url=?"));
680 select_statement.BindString(0, url.url.spec());
681 if (select_statement.Step())
682 return select_statement.ColumnInt(0);
684 return kRankOfNonExistingURL;
687 // Remove the record for this URL. Returns true iff removed successfully.
688 bool TopSitesDatabase::RemoveURL(const MostVisitedURL& url) {
689 int old_rank = GetURLRank(url);
690 if (old_rank == kRankOfNonExistingURL)
693 sql::Transaction transaction(db_.get());
695 if (old_rank != kRankOfForcedURL) {
696 // Decrement all following ranks.
697 sql::Statement shift_statement(db_->GetCachedStatement(
700 "SET url_rank = url_rank - 1 "
701 "WHERE url_rank > ?"));
702 shift_statement.BindInt(0, old_rank);
704 if (!shift_statement.Run())
708 sql::Statement delete_statement(
709 db_->GetCachedStatement(SQL_FROM_HERE,
710 "DELETE FROM thumbnails WHERE url = ?"));
711 delete_statement.BindString(0, url.url.spec());
713 if (!delete_statement.Run())
716 return transaction.Commit();
719 sql::Connection* TopSitesDatabase::CreateDB(const base::FilePath& db_name) {
720 scoped_ptr<sql::Connection> db(new sql::Connection());
721 // Settings copied from ThumbnailDatabase.
722 db->set_histogram_tag("TopSites");
723 db->set_error_callback(base::Bind(&DatabaseErrorCallback,
725 db->set_page_size(4096);
726 db->set_cache_size(32);
728 if (!db->Open(db_name))
733 } // namespace history