1 // Copyright 2013 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. 4 5 #include "components/precache/core/precache_url_table.h" 6 7 #include <string> 8 9 #include "base/logging.h" 10 #include "sql/connection.h" 11 #include "sql/statement.h" 12 13 using sql::Statement; 14 15 namespace { 16 17 // Returns the spec of the given URL. 18 std::string GetKey(const GURL& url) { 19 return url.spec(); 20 } 21 22 } // namespace 23 24 namespace precache { 25 26 PrecacheURLTable::PrecacheURLTable() : db_(NULL) {} 27 28 PrecacheURLTable::~PrecacheURLTable() {} 29 30 bool PrecacheURLTable::Init(sql::Connection* db) { 31 DCHECK(!db_); // Init must only be called once. 32 DCHECK(db); // The database connection must be non-NULL. 33 db_ = db; 34 return CreateTableIfNonExistent(); 35 } 36 37 void PrecacheURLTable::AddURL(const GURL& url, 38 const base::Time& precache_time) { 39 Statement statement(db_->GetCachedStatement( 40 SQL_FROM_HERE, 41 "INSERT OR REPLACE INTO precache_urls (url, time) VALUES(?,?)")); 42 43 statement.BindString(0, GetKey(url)); 44 statement.BindInt64(1, precache_time.ToInternalValue()); 45 statement.Run(); 46 } 47 48 bool PrecacheURLTable::HasURL(const GURL& url) { 49 Statement statement(db_->GetCachedStatement( 50 SQL_FROM_HERE, "SELECT time FROM precache_urls WHERE url=?")); 51 52 statement.BindString(0, GetKey(url)); 53 return statement.Step(); 54 } 55 56 void PrecacheURLTable::DeleteURL(const GURL& url) { 57 Statement statement(db_->GetCachedStatement( 58 SQL_FROM_HERE, "DELETE FROM precache_urls WHERE url=?")); 59 60 statement.BindString(0, GetKey(url)); 61 statement.Run(); 62 } 63 64 void PrecacheURLTable::DeleteAllPrecachedBefore(const base::Time& delete_end) { 65 Statement statement(db_->GetCachedStatement( 66 SQL_FROM_HERE, "DELETE FROM precache_urls WHERE time < ?")); 67 68 statement.BindInt64(0, delete_end.ToInternalValue()); 69 statement.Run(); 70 } 71 72 void PrecacheURLTable::GetAllDataForTesting(std::map<GURL, base::Time>* map) { 73 map->clear(); 74 75 Statement statement(db_->GetCachedStatement( 76 SQL_FROM_HERE, "SELECT url, time FROM precache_urls")); 77 78 while (statement.Step()) { 79 GURL url = GURL(statement.ColumnString(0)); 80 (*map)[url] = base::Time::FromInternalValue(statement.ColumnInt64(1)); 81 } 82 } 83 84 bool PrecacheURLTable::CreateTableIfNonExistent() { 85 return db_->Execute( 86 "CREATE TABLE IF NOT EXISTS precache_urls (url TEXT PRIMARY KEY, time " 87 "INTEGER)"); 88 } 89 90 } // namespace precache 91