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

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