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.
5 #include "components/webdata/common/web_database_backend.h"
8 #include "base/location.h"
9 #include "components/webdata/common/web_data_request_manager.h"
10 #include "components/webdata/common/web_database.h"
11 #include "components/webdata/common/web_database_table.h"
16 WebDatabaseBackend::WebDatabaseBackend(
19 const scoped_refptr
<base::SingleThreadTaskRunner
>& db_thread
)
20 : base::RefCountedDeleteOnMessageLoop
<WebDatabaseBackend
>(db_thread
),
22 request_manager_(new WebDataRequestManager()),
23 init_status_(sql::INIT_FAILURE
),
24 init_complete_(false),
28 void WebDatabaseBackend::AddTable(scoped_ptr
<WebDatabaseTable
> table
) {
30 tables_
.push_back(table
.release());
33 void WebDatabaseBackend::InitDatabase() {
34 LoadDatabaseIfNecessary();
36 delegate_
->DBLoaded(init_status_
);
40 sql::InitStatus
WebDatabaseBackend::LoadDatabaseIfNecessary() {
41 if (init_complete_
|| db_path_
.empty()) {
44 init_complete_
= true;
45 db_
.reset(new WebDatabase());
47 for (ScopedVector
<WebDatabaseTable
>::iterator it
= tables_
.begin();
48 it
!= tables_
.end(); ++it
) {
52 init_status_
= db_
->Init(db_path_
);
53 if (init_status_
!= sql::INIT_OK
) {
54 LOG(ERROR
) << "Cannot initialize the web database: " << init_status_
;
59 db_
->BeginTransaction();
63 void WebDatabaseBackend::ShutdownDatabase() {
64 if (db_
&& init_status_
== sql::INIT_OK
)
65 db_
->CommitTransaction();
67 init_complete_
= true; // Ensures the init sequence is not re-run.
68 init_status_
= sql::INIT_FAILURE
;
71 void WebDatabaseBackend::DBWriteTaskWrapper(
72 const WebDatabaseService::WriteTask
& task
,
73 scoped_ptr
<WebDataRequest
> request
) {
74 if (request
->IsCancelled())
77 ExecuteWriteTask(task
);
78 request_manager_
->RequestCompleted(request
.Pass());
81 void WebDatabaseBackend::ExecuteWriteTask(
82 const WebDatabaseService::WriteTask
& task
) {
83 LoadDatabaseIfNecessary();
84 if (db_
&& init_status_
== sql::INIT_OK
) {
85 WebDatabase::State state
= task
.Run(db_
.get());
86 if (state
== WebDatabase::COMMIT_NEEDED
)
91 void WebDatabaseBackend::DBReadTaskWrapper(
92 const WebDatabaseService::ReadTask
& task
,
93 scoped_ptr
<WebDataRequest
> request
) {
94 if (request
->IsCancelled())
97 request
->SetResult(ExecuteReadTask(task
).Pass());
98 request_manager_
->RequestCompleted(request
.Pass());
101 scoped_ptr
<WDTypedResult
> WebDatabaseBackend::ExecuteReadTask(
102 const WebDatabaseService::ReadTask
& task
) {
103 LoadDatabaseIfNecessary();
104 if (db_
&& init_status_
== sql::INIT_OK
) {
105 return task
.Run(db_
.get());
107 return scoped_ptr
<WDTypedResult
>();
110 WebDatabaseBackend::~WebDatabaseBackend() {
114 void WebDatabaseBackend::Commit() {
116 DCHECK_EQ(sql::INIT_OK
, init_status_
);
117 db_
->CommitTransaction();
118 db_
->BeginTransaction();