| OLD | NEW |
| (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/background/request_queue_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/sequenced_task_runner.h" |
| 13 #include "base/threading/thread_task_runner_handle.h" |
| 14 #include "components/offline_pages/background/save_page_request.h" |
| 15 #include "sql/connection.h" |
| 16 #include "sql/statement.h" |
| 17 #include "sql/transaction.h" |
| 18 |
| 19 namespace offline_pages { |
| 20 |
| 21 namespace { |
| 22 |
| 23 // This is a macro instead of a const so that |
| 24 // it can be used inline in other SQL statements below. |
| 25 #define REQUEST_QUEUE_TABLE_NAME "request_queue_v1" |
| 26 |
| 27 // New columns should be added at the end of the list in order to avoid |
| 28 // complicated table upgrade. |
| 29 const char kOfflinePagesColumns[] = |
| 30 "(request_id INTEGER PRIMARY KEY NOT NULL," |
| 31 " creation_time INTEGER NOT NULL," |
| 32 " activation_time INTEGER NOT NULL DEFAULT 0," |
| 33 " last_attempt_time INTEGER NOT NULL DEFAULT 0," |
| 34 " attempt_count INTEGER NOT NULL," |
| 35 " url VARCHAR NOT NULL," |
| 36 " client_namespace VARCHAR NOT NULL," |
| 37 " client_id VARCHAR NOT NULL" |
| 38 ")"; |
| 39 |
| 40 // Defines indices of the columns in a SELECT * FROM query. Should be kept in |
| 41 // sync with above. |
| 42 enum : int { |
| 43 RQ_REQUEST_ID, |
| 44 RQ_CREATION_TIME, |
| 45 RQ_ACTIVATION_TIME, |
| 46 RQ_LAST_ATTMEPT_TIME, |
| 47 RQ_ATTEMPT_COUNT, |
| 48 RQ_URL, |
| 49 RQ_CLIENT_NAMESPACE, |
| 50 RQ_CLIENT_ID, |
| 51 }; |
| 52 |
| 53 enum class RequestExistsResult { |
| 54 SQL_FAILED, |
| 55 REQUEST_EXISTS, |
| 56 REQUEST_DOES_NOT_EXIST, |
| 57 }; |
| 58 |
| 59 // This is cloned from //content/browser/appcache/appcache_database.cc |
| 60 struct TableInfo { |
| 61 const char* table_name; |
| 62 const char* columns; |
| 63 }; |
| 64 |
| 65 const TableInfo kRequestQueueTable{REQUEST_QUEUE_TABLE_NAME, |
| 66 kOfflinePagesColumns}; |
| 67 |
| 68 bool CreateTable(sql::Connection* db, const TableInfo& table_info) { |
| 69 std::string sql("CREATE TABLE "); |
| 70 sql += table_info.table_name; |
| 71 sql += table_info.columns; |
| 72 return db->Execute(sql.c_str()); |
| 73 } |
| 74 |
| 75 bool CreateSchema(sql::Connection* db) { |
| 76 // If you create a transaction but don't Commit() it is automatically |
| 77 // rolled back by its destructor when it falls out of scope. |
| 78 sql::Transaction transaction(db); |
| 79 if (!transaction.Begin()) |
| 80 return false; |
| 81 |
| 82 if (!db->DoesTableExist(kRequestQueueTable.table_name)) { |
| 83 if (!CreateTable(db, kRequestQueueTable)) |
| 84 return false; |
| 85 } |
| 86 |
| 87 // TODO(fgorski): Add indices here. |
| 88 return transaction.Commit(); |
| 89 } |
| 90 |
| 91 bool DeleteByRequestId(sql::Connection* db, int64_t request_id) { |
| 92 static const char kSql[] = |
| 93 "DELETE FROM " REQUEST_QUEUE_TABLE_NAME " WHERE request_id=?"; |
| 94 sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); |
| 95 statement.BindInt64(0, request_id); |
| 96 LOG(ERROR) << "In DeleteRequestById: " |
| 97 << request_id; // statement.GetSQLStatement(); |
| 98 return statement.Run(); |
| 99 } |
| 100 |
| 101 // Create a save page request from a SQL result. Expects complete rows with |
| 102 // all columns present. |
| 103 SavePageRequest MakeSavePageRequest(sql::Statement* statement) { |
| 104 int64_t id = statement->ColumnInt64(RQ_REQUEST_ID); |
| 105 GURL url(statement->ColumnString(RQ_URL)); |
| 106 ClientId client_id(statement->ColumnString(RQ_CLIENT_NAMESPACE), |
| 107 statement->ColumnString(RQ_CLIENT_ID)); |
| 108 int64_t attempt_count = statement->ColumnInt64(RQ_ATTEMPT_COUNT); |
| 109 base::Time creation_time = |
| 110 base::Time::FromInternalValue(statement->ColumnInt64(RQ_CREATION_TIME)); |
| 111 base::Time activation_time = |
| 112 base::Time::FromInternalValue(statement->ColumnInt64(RQ_ACTIVATION_TIME)); |
| 113 |
| 114 SavePageRequest request(id, url, client_id, creation_time, activation_time); |
| 115 base::Time last_attempt_time = base::Time::FromInternalValue( |
| 116 statement->ColumnInt64(RQ_LAST_ATTMEPT_TIME)); |
| 117 request.set_last_attempt_time(last_attempt_time); |
| 118 request.set_attempt_count(attempt_count); |
| 119 |
| 120 return request; |
| 121 } |
| 122 |
| 123 RequestExistsResult RequestExists(sql::Connection* db, int64_t request_id) { |
| 124 const char kSql[] = |
| 125 "SELECT COUNT(*) FROM " REQUEST_QUEUE_TABLE_NAME " WHERE request_id = ?"; |
| 126 sql::Statement statement(db->GetUniqueStatement(kSql)); |
| 127 statement.BindInt64(0, request_id); |
| 128 if (!statement.Step()) { |
| 129 LOG(ERROR) << "Failed to check if request exists: " << request_id |
| 130 << ", SQL statement: " << statement.GetSQLStatement(); |
| 131 return RequestExistsResult::SQL_FAILED; |
| 132 } |
| 133 return statement.ColumnInt64(0) ? RequestExistsResult::REQUEST_EXISTS |
| 134 : RequestExistsResult::REQUEST_DOES_NOT_EXIST; |
| 135 } |
| 136 |
| 137 RequestQueueStore::UpdateStatus InsertOrReplace( |
| 138 sql::Connection* db, |
| 139 const SavePageRequest& request) { |
| 140 // In order to use the enums in the Bind* methods, keep the order of fields |
| 141 // the same as in the definition/select query. |
| 142 const char kInsertSql[] = |
| 143 "INSERT OR REPLACE INTO " REQUEST_QUEUE_TABLE_NAME |
| 144 " (request_id, creation_time, activation_time, last_attempt_time, " |
| 145 " attempt_count, url, client_namespace, client_id) " |
| 146 " VALUES " |
| 147 " (?, ?, ?, ?, ?, ?, ?, ?)"; |
| 148 |
| 149 // Checking if a request exists and adding/updating it will happen in a single |
| 150 // transaction. |
| 151 sql::Transaction transaction(db); |
| 152 if (!transaction.Begin()) { |
| 153 LOG(ERROR) << "Failed to start transaction on InsertOrReplace."; |
| 154 return RequestQueueStore::UpdateStatus::FAILED; |
| 155 } |
| 156 |
| 157 RequestExistsResult exists = RequestExists(db, request.request_id()); |
| 158 if (exists == RequestExistsResult::SQL_FAILED) { |
| 159 LOG(ERROR) << "Failed to check if request exists: " << request.request_id(); |
| 160 return RequestQueueStore::UpdateStatus::FAILED; |
| 161 } |
| 162 |
| 163 RequestQueueStore::UpdateStatus status = |
| 164 exists == RequestExistsResult::REQUEST_EXISTS |
| 165 ? RequestQueueStore::UpdateStatus::UPDATED |
| 166 : RequestQueueStore::UpdateStatus::ADDED; |
| 167 |
| 168 sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kInsertSql)); |
| 169 statement.BindInt64(RQ_REQUEST_ID, request.request_id()); |
| 170 statement.BindString(RQ_URL, request.url().spec()); |
| 171 statement.BindString(RQ_CLIENT_NAMESPACE, request.client_id().name_space); |
| 172 statement.BindString(RQ_CLIENT_ID, request.client_id().id); |
| 173 statement.BindInt64(RQ_CREATION_TIME, |
| 174 request.creation_time().ToInternalValue()); |
| 175 statement.BindInt64(RQ_ACTIVATION_TIME, |
| 176 request.activation_time().ToInternalValue()); |
| 177 statement.BindInt64(RQ_LAST_ATTMEPT_TIME, |
| 178 request.last_attempt_time().ToInternalValue()); |
| 179 statement.BindInt64(RQ_ATTEMPT_COUNT, request.attempt_count()); |
| 180 |
| 181 if (!statement.Run() || !transaction.Commit()) { |
| 182 LOG(ERROR) << "Failed to add/update a request: " << request.request_id(); |
| 183 return RequestQueueStore::UpdateStatus::FAILED; |
| 184 } |
| 185 |
| 186 return status; |
| 187 } |
| 188 |
| 189 bool InitDatabase(sql::Connection* db, const base::FilePath& path) { |
| 190 db->set_page_size(4096); |
| 191 db->set_cache_size(500); |
| 192 db->set_histogram_tag("BackgroundRequestQueue"); |
| 193 db->set_exclusive_locking(); |
| 194 |
| 195 base::File::Error err; |
| 196 if (!base::CreateDirectoryAndGetError(path.DirName(), &err)) { |
| 197 LOG(ERROR) << "Failed to create background request queue db directory: " |
| 198 << base::File::ErrorToString(err); |
| 199 return false; |
| 200 } |
| 201 if (!db->Open(path)) { |
| 202 LOG(ERROR) << "Failed to open database"; |
| 203 return false; |
| 204 } |
| 205 db->Preload(); |
| 206 |
| 207 return CreateSchema(db); |
| 208 } |
| 209 |
| 210 } // anonymous namespace |
| 211 |
| 212 RequestQueueStoreSQL::RequestQueueStoreSQL( |
| 213 scoped_refptr<base::SequencedTaskRunner> background_task_runner, |
| 214 const base::FilePath& path) |
| 215 : background_task_runner_(std::move(background_task_runner)), |
| 216 db_file_path_(path.AppendASCII("RequestQueue.db")), |
| 217 weak_ptr_factory_(this) { |
| 218 OpenConnection(); |
| 219 } |
| 220 |
| 221 RequestQueueStoreSQL::~RequestQueueStoreSQL() { |
| 222 if (db_.get() && |
| 223 !background_task_runner_->DeleteSoon(FROM_HERE, db_.release())) { |
| 224 DLOG(WARNING) << "SQL database will not be deleted."; |
| 225 } |
| 226 } |
| 227 |
| 228 // static |
| 229 void RequestQueueStoreSQL::OpenConnectionSync( |
| 230 sql::Connection* db, |
| 231 scoped_refptr<base::SingleThreadTaskRunner> runner, |
| 232 const base::FilePath& path, |
| 233 const base::Callback<void(bool)>& callback) { |
| 234 bool success = InitDatabase(db, path); |
| 235 runner->PostTask(FROM_HERE, base::Bind(callback, success)); |
| 236 } |
| 237 |
| 238 // static |
| 239 void RequestQueueStoreSQL::GetRequestsSync( |
| 240 sql::Connection* db, |
| 241 scoped_refptr<base::SingleThreadTaskRunner> runner, |
| 242 const GetRequestsCallback& callback) { |
| 243 const char kSql[] = "SELECT * FROM " REQUEST_QUEUE_TABLE_NAME; |
| 244 |
| 245 sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); |
| 246 |
| 247 std::vector<SavePageRequest> result; |
| 248 while (statement.Step()) { |
| 249 result.push_back(MakeSavePageRequest(&statement)); |
| 250 } |
| 251 |
| 252 runner->PostTask(FROM_HERE, |
| 253 base::Bind(callback, statement.Succeeded(), result)); |
| 254 } |
| 255 |
| 256 // static |
| 257 void RequestQueueStoreSQL::AddOrUpdateRequestSync( |
| 258 sql::Connection* db, |
| 259 scoped_refptr<base::SingleThreadTaskRunner> runner, |
| 260 const SavePageRequest& request, |
| 261 const UpdateCallback& callback) { |
| 262 // TODO(fgorski): add UMA metrics here. |
| 263 RequestQueueStore::UpdateStatus status = InsertOrReplace(db, request); |
| 264 runner->PostTask(FROM_HERE, base::Bind(callback, status)); |
| 265 } |
| 266 |
| 267 // static |
| 268 void RequestQueueStoreSQL::RemoveRequestsSync( |
| 269 sql::Connection* db, |
| 270 scoped_refptr<base::SingleThreadTaskRunner> runner, |
| 271 const std::vector<int64_t>& request_ids, |
| 272 const RemoveCallback& callback) { |
| 273 // TODO(fgorski): add UMA metrics here. |
| 274 |
| 275 // If you create a transaction but don't Commit() it is automatically |
| 276 // rolled back by its destructor when it falls out of scope. |
| 277 sql::Transaction transaction(db); |
| 278 if (!transaction.Begin()) { |
| 279 runner->PostTask(FROM_HERE, base::Bind(callback, false, 0)); |
| 280 return; |
| 281 } |
| 282 int count = 0; |
| 283 for (auto request_id : request_ids) { |
| 284 RequestExistsResult exists = RequestExists(db, request_id); |
| 285 if (exists == RequestExistsResult::SQL_FAILED) { |
| 286 runner->PostTask(FROM_HERE, base::Bind(callback, false, 0)); |
| 287 return; |
| 288 } |
| 289 if (exists == RequestExistsResult::REQUEST_DOES_NOT_EXIST) |
| 290 continue; |
| 291 |
| 292 ++count; |
| 293 if (!DeleteByRequestId(db, request_id)) { |
| 294 runner->PostTask(FROM_HERE, base::Bind(callback, false, 0)); |
| 295 return; |
| 296 } |
| 297 } |
| 298 |
| 299 if (!transaction.Commit()) { |
| 300 runner->PostTask(FROM_HERE, base::Bind(callback, false, 0)); |
| 301 return; |
| 302 } |
| 303 |
| 304 runner->PostTask(FROM_HERE, base::Bind(callback, true, count)); |
| 305 } |
| 306 |
| 307 // static |
| 308 void RequestQueueStoreSQL::ResetSync( |
| 309 std::unique_ptr<sql::Connection> db, |
| 310 scoped_refptr<base::SingleThreadTaskRunner> runner, |
| 311 const ResetCallback& callback) { |
| 312 // This method deletes the content of the whole store. It should be used with |
| 313 // caution, e.g. when recovering from situation, in which the contents of the |
| 314 // store does not make sense and cannot be converted to reasonable requests. |
| 315 const char kSql[] = "DELETE FROM " REQUEST_QUEUE_TABLE_NAME; |
| 316 sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); |
| 317 runner->PostTask(FROM_HERE, base::Bind(callback, statement.Run())); |
| 318 } |
| 319 |
| 320 void RequestQueueStoreSQL::GetRequests(const GetRequestsCallback& callback) { |
| 321 DCHECK(db_.get()); |
| 322 if (!db_.get()) { |
| 323 // Nothing to do, but post a callback instead of calling directly |
| 324 // to preserve the async style behavior to prevent bugs. |
| 325 base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 326 FROM_HERE, base::Bind(callback, false, std::vector<SavePageRequest>())); |
| 327 return; |
| 328 } |
| 329 |
| 330 background_task_runner_->PostTask( |
| 331 FROM_HERE, base::Bind(&RequestQueueStoreSQL::GetRequestsSync, db_.get(), |
| 332 base::ThreadTaskRunnerHandle::Get(), callback)); |
| 333 } |
| 334 |
| 335 void RequestQueueStoreSQL::AddOrUpdateRequest(const SavePageRequest& request, |
| 336 const UpdateCallback& callback) { |
| 337 DCHECK(db_.get()); |
| 338 if (!db_.get()) { |
| 339 // Nothing to do, but post a callback instead of calling directly |
| 340 // to preserve the async style behavior to prevent bugs. |
| 341 base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 342 FROM_HERE, base::Bind(callback, UpdateStatus::FAILED)); |
| 343 return; |
| 344 } |
| 345 |
| 346 background_task_runner_->PostTask( |
| 347 FROM_HERE, |
| 348 base::Bind(&RequestQueueStoreSQL::AddOrUpdateRequestSync, db_.get(), |
| 349 base::ThreadTaskRunnerHandle::Get(), request, callback)); |
| 350 } |
| 351 |
| 352 void RequestQueueStoreSQL::RemoveRequests( |
| 353 const std::vector<int64_t>& request_ids, |
| 354 const RemoveCallback& callback) { |
| 355 DCHECK(db_.get()); |
| 356 if (!db_.get()) { |
| 357 // Nothing to do, but post a callback instead of calling directly |
| 358 // to preserve the async style behavior to prevent bugs. |
| 359 base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 360 FROM_HERE, base::Bind(callback, false, 0)); |
| 361 return; |
| 362 } |
| 363 |
| 364 if (request_ids.empty()) { |
| 365 // Nothing to do, but post a callback instead of calling directly |
| 366 // to preserve the async style behavior to prevent bugs. |
| 367 base::ThreadTaskRunnerHandle::Get()->PostTask( |
| 368 FROM_HERE, base::Bind(callback, true, 0)); |
| 369 return; |
| 370 } |
| 371 |
| 372 background_task_runner_->PostTask( |
| 373 FROM_HERE, |
| 374 base::Bind(&RequestQueueStoreSQL::RemoveRequestsSync, db_.get(), |
| 375 base::ThreadTaskRunnerHandle::Get(), request_ids, callback)); |
| 376 } |
| 377 |
| 378 void RequestQueueStoreSQL::Reset(const ResetCallback& callback) { |
| 379 DCHECK(db_.get()); |
| 380 if (!db_.get()) { |
| 381 // Nothing to do, but post a callback instead of calling directly |
| 382 // to preserve the async style behavior to prevent bugs. |
| 383 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, |
| 384 base::Bind(callback, false)); |
| 385 return; |
| 386 } |
| 387 |
| 388 background_task_runner_->PostTask( |
| 389 FROM_HERE, |
| 390 base::Bind(&RequestQueueStoreSQL::ResetSync, base::Passed(&db_), |
| 391 base::ThreadTaskRunnerHandle::Get(), callback)); |
| 392 } |
| 393 |
| 394 void RequestQueueStoreSQL::OpenConnection() { |
| 395 DCHECK(!db_); |
| 396 db_.reset(new sql::Connection()); |
| 397 background_task_runner_->PostTask( |
| 398 FROM_HERE, |
| 399 base::Bind(&RequestQueueStoreSQL::OpenConnectionSync, db_.get(), |
| 400 base::ThreadTaskRunnerHandle::Get(), db_file_path_, |
| 401 base::Bind(&RequestQueueStoreSQL::OnOpenConnectionDone, |
| 402 weak_ptr_factory_.GetWeakPtr()))); |
| 403 } |
| 404 |
| 405 void RequestQueueStoreSQL::OnOpenConnectionDone(bool success) { |
| 406 DCHECK(db_.get()); |
| 407 |
| 408 // Unfortunately we were not able to open DB connection. |
| 409 if (!success) { |
| 410 LOG(ERROR) << "Database creation fialed."; |
| 411 db_.reset(); |
| 412 } |
| 413 } |
| 414 |
| 415 } // namespace offline_pages |
| OLD | NEW |