Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(63)

Side by Side Diff: components/offline_pages/offline_page_metadata_store_sql.cc

Issue 1834563002: initial add of SQL based storage (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: address comments Created 4 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « components/offline_pages/offline_page_metadata_store_sql.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright 2016 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/offline_pages/offline_page_metadata_store_sql.h"
6
7 #include "base/bind.h"
8 #include "base/files/file_path.h"
9 #include "base/files/file_util.h"
10 #include "base/location.h"
jianli 2016/04/01 20:57:59 nit: also include base/logging.h
bburns 2016/04/01 22:51:44 Done.
11 #include "base/metrics/histogram_macros.h"
12 #include "base/sequenced_task_runner.h"
13 #include "base/thread_task_runner_handle.h"
14 #include "components/offline_pages/offline_page_item.h"
15 #include "sql/connection.h"
16 #include "sql/error_delegate_util.h"
17 #include "sql/meta_table.h"
18 #include "sql/statement.h"
19 #include "sql/transaction.h"
20
21 namespace offline_pages {
22
23 namespace {
24
25 const int kCurrentVersion = 1;
26 const int kCompatibleVersion = 1;
27
28 // This is a macro instead of a const so that
29 // it can be used inline in other SQL statements below.
30 #define OFFLINE_PAGES_TABLE_NAME "offlinepages"
31
32 const char kOfflinePagesColumns[] =
33 "(offline_id INTEGER NOT NULL,"
34 " client_namespace VARCHAR(256),"
35 " client_id VARCHAR(256),"
36 " online_url VARCHAR(2048),"
37 " offline_url VARCHAR(2048),"
38 " version INTEGER,"
39 " creation_time INTEGER,"
40 " file_path VARCHAR(1024),"
41 " file_size INTEGER,"
42 " last_access_time INTEGER,"
43 " access_count INTEGER,"
44 " status INTEGER,"
45 " user_initiated BOOLEAN,"
46 " UNIQUE(offline_id))";
47
48 // This is cloned from //content/browser/appcache/appcache_database.cc
49 struct TableInfo {
50 const char* table_name;
51 const char* columns;
52 };
53
54 const TableInfo kOfflinePagesTable{OFFLINE_PAGES_TABLE_NAME,
55 kOfflinePagesColumns};
56
57 // This enum is used to define the indices for the columns in each row
58 // that hold the different pieces of offline page.
59 enum : int {
60 OP_OFFLINE_ID = 0,
61 OP_CLIENT_NAMESPACE,
62 OP_CLIENT_ID,
63 OP_ONLINE_URL,
64 OP_OFFLINE_URL,
65 OP_VERSION,
66 OP_CREATION_TIME,
67 OP_FILE_PATH,
68 OP_FILE_SIZE,
69 OP_LAST_ACCESS_TIME,
70 OP_ACCESS_COUNT,
71 OP_STATUS,
72 OP_USER_INITIATED
73 };
74
75 bool CreateTable(sql::Connection* db,
76 const char* table_name,
77 const char* columns) {
78 std::string sql("CREATE TABLE ");
79 sql += table_name;
80 sql += columns;
81 return db->Execute(sql.c_str());
82 }
83
84 bool CreateSchema(sql::MetaTable* meta_table, sql::Connection* db) {
85 // If you create a transaction but don't Commit() it is automatically
86 // rolled back by its destructor when it falls out of scope.
87 sql::Transaction transaction(db);
88 if (!transaction.Begin())
89 return false;
90
91 if (!meta_table->Init(db, kCurrentVersion, kCompatibleVersion))
92 return false;
93
94 if (!CreateTable(db, OFFLINE_PAGES_TABLE_NAME, kOfflinePagesColumns))
95 return false;
96
97 // TODO(bburns): Add indices here.
98 return transaction.Commit();
99 }
100
101 bool DeleteByOfflineId(sql::Connection* db, int64_t offline_id) {
102 const char kSql[] =
103 "DELETE FROM " OFFLINE_PAGES_TABLE_NAME " WHERE offline_id=?";
104 sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql));
105 statement.BindInt64(0, offline_id);
106 return statement.Run();
107 }
108
109 // Create an offline page item from a SQL result. Expects complete rows with
110 // all columns present.
111 OfflinePageItem MakeOfflinePageItem(sql::Statement* statement) {
112 int64_t id = statement->ColumnInt64(OP_OFFLINE_ID);
113 GURL url(statement->ColumnString(OP_ONLINE_URL));
114 ClientId client_id(statement->ColumnString(OP_CLIENT_NAMESPACE),
115 statement->ColumnString(OP_CLIENT_ID));
116 #if defined(OS_POSIX)
117 base::FilePath path(statement->ColumnString(OP_FILE_PATH));
118 #elif defined(OS_WIN)
119 base::FilePath path(base::UTF8ToWide(statement->ColumnString(OP_FILE_PATH)));
120 #endif
121 int64_t file_size = statement->ColumnInt64(OP_FILE_SIZE);
122 base::Time creation_time =
123 base::Time::FromInternalValue(statement->ColumnInt64(OP_CREATION_TIME));
124
125 OfflinePageItem item(url, id, client_id, path, file_size, creation_time);
126 item.last_access_time = base::Time::FromInternalValue(
127 statement->ColumnInt64(OP_LAST_ACCESS_TIME));
128 item.version = statement->ColumnInt(OP_VERSION);
129 item.access_count = statement->ColumnInt(OP_ACCESS_COUNT);
130 return item;
131 }
132
133 bool InsertOrReplace(sql::Connection* db, const OfflinePageItem& item) {
134 const char kSql[] =
135 "INSERT OR REPLACE INTO " OFFLINE_PAGES_TABLE_NAME
136 " (offline_id, online_url, client_namespace, client_id, file_path, "
137 "file_size, creation_time, last_access_time, version, access_count)"
138 " VALUES "
139 " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
140
141 sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql));
142 statement.BindInt64(0, item.offline_id);
143 statement.BindString(1, item.url.spec());
144 statement.BindString(2, item.client_id.name_space);
145 statement.BindString(3, item.client_id.id);
146 std::string path_string;
147 #if defined(OS_POSIX)
148 path_string = item.file_path.value();
149 #elif defined(OS_WIN)
150 path_string = base::WideToUTF8(item.file_path.value());
151 #endif
152 statement.BindString(4, path_string);
153 statement.BindInt64(5, item.file_size);
154 statement.BindInt64(6, item.creation_time.ToInternalValue());
155 statement.BindInt64(7, item.last_access_time.ToInternalValue());
156 statement.BindInt(8, item.version);
157 statement.BindInt(9, item.access_count);
158 return statement.Run();
159 }
160
161 } // anonymous namespace
162
163 OfflinePageMetadataStoreSQL::OfflinePageMetadataStoreSQL(
164 scoped_refptr<base::SequencedTaskRunner> background_task_runner,
165 const base::FilePath& path)
166 : background_task_runner_(background_task_runner),
167 db_file_path_(path.AppendASCII("OfflinePages.db")),
168 use_in_memory_(false),
169 weak_ptr_factory_(this) {}
170
171 OfflinePageMetadataStoreSQL::~OfflinePageMetadataStoreSQL() {}
172
173 void OfflinePageMetadataStoreSQL::LoadSync(
174 scoped_refptr<base::SingleThreadTaskRunner> runner,
175 const LoadCallback& callback) {
176 bool opened = false;
177 db_.reset(new sql::Connection);
178 meta_table_.reset(new sql::MetaTable);
179
180 if (use_in_memory_) {
181 opened = db_->OpenInMemory();
182 } else {
183 base::File::Error err;
184 if (!base::CreateDirectoryAndGetError(db_file_path_.DirName(), &err)) {
185 LOG(ERROR) << "Failed to create offline pages db directory: "
186 << base::File::ErrorToString(err);
187 } else {
188 opened = db_->Open(db_file_path_);
189 if (opened)
190 db_->Preload();
191 }
192 }
193 if (!opened) {
194 LOG(ERROR) << "Failed to open database";
195 NotifyLoadResult(runner, callback, STORE_INIT_FAILED,
196 std::vector<OfflinePageItem>());
197 return;
198 }
199
200 if (!sql::MetaTable::DoesTableExist(db_.get())) {
201 if (!CreateSchema(meta_table_.get(), db_.get())) {
202 LOG(ERROR) << "Failed to create schema";
203 NotifyLoadResult(runner, callback, STORE_INIT_FAILED,
204 std::vector<OfflinePageItem>());
205 return;
206 }
207 } else if (!meta_table_->Init(db_.get(), kCurrentVersion,
208 kCompatibleVersion)) {
209 LOG(ERROR) << "Failed to initialize database";
210 NotifyLoadResult(runner, callback, STORE_INIT_FAILED,
211 std::vector<OfflinePageItem>());
212 return;
213 }
214
215 if (meta_table_->GetCompatibleVersionNumber() > kCurrentVersion) {
216 LOG(WARNING) << "Offline database is too new.";
217 NotifyLoadResult(runner, callback, STORE_INIT_FAILED,
218 std::vector<OfflinePageItem>());
219 return;
220 }
221
222 const char kSql[] = "SELECT * FROM " OFFLINE_PAGES_TABLE_NAME;
223
224 sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
225
226 std::vector<OfflinePageItem> result;
227 while (statement.Step()) {
228 result.push_back(MakeOfflinePageItem(&statement));
229 }
230
231 if (statement.Succeeded()) {
232 NotifyLoadResult(runner, callback, LOAD_SUCCEEDED, result);
233 } else {
234 NotifyLoadResult(runner, callback, STORE_LOAD_FAILED,
235 std::vector<OfflinePageItem>());
236 }
237 }
238
239 void OfflinePageMetadataStoreSQL::AddOrUpdateOfflinePageSync(
240 const OfflinePageItem& offline_page,
241 scoped_refptr<base::SingleThreadTaskRunner> runner,
242 const UpdateCallback& callback) {
243 DCHECK(db_.get());
244 // TODO(bburns): add UMA metrics here (and for levelDB).
245 bool ok = InsertOrReplace(db_.get(), offline_page);
246 runner->PostTask(FROM_HERE, base::Bind(callback, ok));
247 }
248
249 void OfflinePageMetadataStoreSQL::RemoveOfflinePagesSync(
250 const std::vector<int64_t>& offline_ids,
251 scoped_refptr<base::SingleThreadTaskRunner> runner,
252 const UpdateCallback& callback) {
253 DCHECK(db_.get());
254 // TODO(bburns): add UMA metrics here (and for levelDB).
255
256 // If you create a transaction but don't Commit() it is automatically
257 // rolled back by its destructor when it falls out of scope.
258 sql::Transaction transaction(db_.get());
259 if (!transaction.Begin()) {
260 runner->PostTask(FROM_HERE, base::Bind(callback, false));
261 return;
262 }
263 for (auto offline_id : offline_ids) {
264 if (!DeleteByOfflineId(db_.get(), offline_id)) {
265 runner->PostTask(FROM_HERE, base::Bind(callback, false));
266 return;
267 }
268 }
269
270 bool success = transaction.Commit();
271 runner->PostTask(FROM_HERE, base::Bind(callback, success));
272 }
273
274 void OfflinePageMetadataStoreSQL::ResetSync(
275 scoped_refptr<base::SingleThreadTaskRunner> runner,
276 const ResetCallback& callback) {
277 const char kSql[] = "DELETE * FROM " OFFLINE_PAGES_TABLE_NAME;
278 sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
279 if (!statement.Run()) {
280 runner->PostTask(FROM_HERE, base::Bind(callback, false));
281 return;
282 }
283 meta_table_.reset();
284 db_.reset();
285 weak_ptr_factory_.InvalidateWeakPtrs();
286
287 runner->PostTask(FROM_HERE, base::Bind(callback, true));
288 }
289
290 void OfflinePageMetadataStoreSQL::NotifyLoadResult(
291 scoped_refptr<base::SingleThreadTaskRunner> runner,
292 const LoadCallback& callback,
293 LoadStatus status,
294 const std::vector<OfflinePageItem>& result) {
295 // TODO(bburns): Switch to SQL specific UMA metrics.
296 UMA_HISTOGRAM_ENUMERATION("OfflinePages.LoadStatus", status,
297 OfflinePageMetadataStore::LOAD_STATUS_COUNT);
298 if (status == LOAD_SUCCEEDED) {
299 UMA_HISTOGRAM_COUNTS("OfflinePages.SavedPageCount", result.size());
300 } else {
301 DVLOG(1) << "Offline pages database loading failed: " << status;
302 meta_table_.reset();
303 db_.reset();
304 }
305 runner->PostTask(FROM_HERE, base::Bind(callback, status, result));
306 }
307
308 void OfflinePageMetadataStoreSQL::Load(const LoadCallback& callback) {
309 background_task_runner_->PostTask(
310 FROM_HERE, base::Bind(&OfflinePageMetadataStoreSQL::LoadSync,
311 weak_ptr_factory_.GetWeakPtr(),
312 base::ThreadTaskRunnerHandle::Get(), callback));
313 }
314
315 void OfflinePageMetadataStoreSQL::AddOrUpdateOfflinePage(
316 const OfflinePageItem& offline_page,
317 const UpdateCallback& callback) {
318 background_task_runner_->PostTask(
319 FROM_HERE,
320 base::Bind(&OfflinePageMetadataStoreSQL::AddOrUpdateOfflinePageSync,
321 weak_ptr_factory_.GetWeakPtr(), offline_page,
322 base::ThreadTaskRunnerHandle::Get(), callback));
323 }
324
325 void OfflinePageMetadataStoreSQL::RemoveOfflinePages(
326 const std::vector<int64_t>& offline_ids,
327 const UpdateCallback& callback) {
328 if (offline_ids.size() == 0) {
329 // Nothing to do, but post a callback instead of calling directly
330 // to preserve the async style behavior to prevent bugs.
331 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
332 base::Bind(callback, true));
333 return;
334 }
335
336 background_task_runner_->PostTask(
337 FROM_HERE,
338 base::Bind(&OfflinePageMetadataStoreSQL::RemoveOfflinePagesSync,
339 weak_ptr_factory_.GetWeakPtr(), offline_ids,
340 base::ThreadTaskRunnerHandle::Get(), callback));
341 }
342
343 void OfflinePageMetadataStoreSQL::Reset(const ResetCallback& callback) {
344 background_task_runner_->PostTask(
345 FROM_HERE, base::Bind(&OfflinePageMetadataStoreSQL::ResetSync,
346 weak_ptr_factory_.GetWeakPtr(),
347 base::ThreadTaskRunnerHandle::Get(), callback));
348 }
349
350 void OfflinePageMetadataStoreSQL::SetInMemoryDatabaseForTesting(
351 bool in_memory) {
352 // Must be called prior to Load(...)
353 DCHECK(db_.get() == NULL);
354
355 use_in_memory_ = in_memory;
356 }
357
358 } // namespace offline_pages
OLDNEW
« no previous file with comments | « components/offline_pages/offline_page_metadata_store_sql.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698