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

Side by Side Diff: webkit/dom_storage/dom_storage_database.cc

Issue 9159020: Create a class to represent a DOM Storage Database. (Closed) Base URL: http://git.chromium.org/chromium/src.git@master
Patch Set: Tidy up. Created 8 years, 10 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
OLDNEW
(Empty)
1 // Copyright (c) 2012 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 "webkit/dom_storage/dom_storage_database.h"
6
7 #include "base/file_util.h"
8 #include "base/logging.h"
9 #include "sql/diagnostic_error_delegate.h"
10 #include "sql/statement.h"
11 #include "sql/transaction.h"
12 #include "third_party/sqlite/sqlite3.h"
13
14 namespace {
15
16 class HistogramUniquifier {
17 public:
18 static const char* name() { return "Sqlite.DomStorageDatabase.Error"; }
19 };
20
21 sql::ErrorDelegate* GetErrorHandlerForDomStorageDatabase() {
22 return new sql::DiagnosticErrorDelegate<HistogramUniquifier>();
23 }
24
25 } // anon namespace
26
27 namespace dom_storage {
28
29 DomStorageDatabase::DomStorageDatabase(const FilePath& file_path)
30 : file_path_(file_path),
31 db_(NULL),
32 failed_to_open_(false),
33 tried_to_recreate_(false) {
34 // Note: in normal use we should never get an empty backing path here.
35 // However, the unit test for this class defines another constructor
36 // that will bypass this check to allow an empty path that signifies
37 // we should operate on an in-memory database for performance/reliability
38 // reasons.
39 DCHECK(!file_path_.empty());
40 }
41
42 DomStorageDatabase::~DomStorageDatabase() {
43 }
44
45 void DomStorageDatabase::ReadAllValues(ValuesMap* result) {
46 if (!LazyOpen(false))
47 return;
48
49 sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE,
50 "SELECT * from ItemTable"));
51 DCHECK(statement.is_valid());
52
53 while (statement.Step()) {
54 string16 key = statement.ColumnString16(0);
55 string16 value;
56 statement.ColumnBlobAsString16(1, &value);
57 (*result)[key] = NullableString16(value, false);
58 }
59 }
60
61 bool DomStorageDatabase::CommitChanges(bool clear_all_first,
62 const ValuesMap& changes) {
63 if (!LazyOpen(!changes.empty()))
64 return false;
65
66 sql::Transaction transaction(db_.get());
67 if (!transaction.Begin())
68 return false;
69
70 if (clear_all_first) {
71 if (!db_->Execute("DELETE FROM ItemTable"))
72 return false;
73 }
74
75 ValuesMap::const_iterator it = changes.begin();
76 for(; it != changes.end(); ++it) {
77 sql::Statement statement;
78 string16 key = it->first;
79 NullableString16 value = it->second;
80 if (value.is_null()) {
81 statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE,
82 "DELETE FROM ItemTable WHERE key=?"));
83 statement.BindString16(0, key);
84 } else {
85 statement.Assign(db_->GetCachedStatement(SQL_FROM_HERE,
86 "INSERT INTO ItemTable VALUES (?,?)"));
87 statement.BindString16(0, key);
88 statement.BindBlob(1, value.string().data(),
89 value.string().length() * sizeof(char16));
90 }
91 DCHECK(statement.is_valid());
92 statement.Run();
93 }
94 return transaction.Commit();
95 }
96
97 bool DomStorageDatabase::LazyOpen(bool create_if_needed) {
98 if (failed_to_open_) {
99 // Don't try to open a database that we know has failed
100 // already.
101 return false;
102 }
103
104 if (IsOpen())
105 return true;
106
107 bool database_exists = file_util::PathExists(file_path_);
108
109 if (!database_exists && !create_if_needed) {
110 // If the file doesn't exist already and we haven't been asked to create
111 // a file on disk, then we don't bother opening the database. This means
112 // we wait until we absolutely need to put something onto disk before we
113 // do so.
114 return false;
115 }
116
117 db_.reset(new sql::Connection());
118 db_->set_error_delegate(GetErrorHandlerForDomStorageDatabase());
119
120 if (file_path_.empty()) {
121 // This code path should only be triggered by unit tests.
122 if (!db_->OpenInMemory()) {
123 LOG(ERROR) << "Unable to open DOM storage database in memory.";
michaeln 2012/02/08 06:11:33 this could probably be a NOTREACHED() instead
benm (inactive) 2012/02/08 14:59:40 Done.
124 failed_to_open_ = true;
125 return false;
126 }
127 } else {
128 if (!db_->Open(file_path_)) {
129 LOG(ERROR) << "Unable to open DOM storage database at "
130 << file_path_.value()
131 << " error: " << db_->GetErrorMessage();
132 if (database_exists && !tried_to_recreate_)
133 return DeleteFileAndRecreate();
134 failed_to_open_ = true;
135 return false;
136 }
137 }
138
139 // Open() may succeed even if the file we try and open is not a database so
140 // we check here that what we've got is something sensible.
141 // TODO(benm): It might be useful to actually verify the output of the
142 // quick_check too and try to recover in the case errors are detected.
143 // However, in the case that the database is corrupted to the point that
144 // SQLite doesn't actually think it's a database,
145 // sql::Connection::GetCachedStatement will DCHECK.
146 if (db_->ExecuteAndReturnErrorCode("PRAGMA quick_check(1)") != SQLITE_OK) {
147 Close();
148 return DeleteFileAndRecreate();
149 }
150
151 // sql::Connection uses UTF-8 encoding, but WebCore style databases use
152 // UTF-16, so ensure we match.
153 ignore_result(db_->Execute("PRAGMA encoding=\"UTF-16\""));
154
155 // If the table doesn't exist, try to create it at the current version.
156 if (!db_->DoesTableExist("ItemTable")) {
157 if (CreateTable())
158 return true;
159 // Couldn't create the table.
160 Close();
161 return DeleteFileAndRecreate();
162 }
163
164 // Table exists, so ensure we're at the right version, upgrading if
165 // necessary.
166 if (UpgradeVersion1To2IfNeeded())
167 return true;
168
169 // We were not able to verify that the database is at the correct version
170 // so close the connection and attempt to recreate the database from
171 // scratch.
172 Close();
173 return DeleteFileAndRecreate();
174 }
175
176 bool DomStorageDatabase::CreateTable() {
177 DCHECK(IsOpen());
178 // Current version is 2.
179 return CreateTableV2();
michaeln 2012/02/08 06:11:33 i still don't see the reason for two CreateTable m
benm (inactive) 2012/02/08 14:59:40 OK, done.
180 }
181
182 bool DomStorageDatabase::CreateTableV2() {
183 DCHECK(IsOpen());
184
185 return db_->Execute(
186 "CREATE TABLE IF NOT EXISTS ItemTable ("
187 "key TEXT UNIQUE ON CONFLICT REPLACE, "
188 "value BLOB NOT NULL ON CONFLICT FAIL)");
189 }
190
191 bool DomStorageDatabase::DeleteFileAndRecreate() {
192 DCHECK(!IsOpen());
193 DCHECK(file_util::PathExists(file_path_));
194
195 // We should only try and do this once.
196 if (tried_to_recreate_)
197 return false;
198
199 tried_to_recreate_ = true;
200
201 // If it's not a directory and we can delete the file, try and open it again.
202 if (!file_util::DirectoryExists(file_path_) &&
203 file_util::Delete(file_path_, false))
204 return LazyOpen(true);
205
206 failed_to_open_ = true;
207 return false;
208 }
209
210 bool DomStorageDatabase::UpgradeVersion1To2IfNeeded() {
211 DCHECK(IsOpen());
212 sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE,
213 "SELECT * FROM ItemTable"));
214 DCHECK(statement.is_valid());
215
216 // Quick check to see if we need to upgrade or not. The single
217 // effect of V1 -> V2 is to change the value column from type
218 // TEXT to type BLOB.
219 sql::ColType value_column_type = statement.DeclaredColumnType(1);
220 if (value_column_type == sql::COLUMN_TYPE_BLOB)
221 return true;
222
223 if (value_column_type != sql::COLUMN_TYPE_TEXT) {
224 // Something is messed up. This is not a V1 database.
225 return false;
226 }
227
228 // Need to migrate from TEXT value column to BLOB.
229 // Store the current database content so we can re-insert
230 // the data into the new V2 table.
231 ValuesMap values;
232 while (statement.Step()) {
233 string16 key = statement.ColumnString16(0);
234 NullableString16 value(statement.ColumnString16(1), false);
235 values[key] = value;
236 }
237
238 sql::Transaction migration(db_.get());
239 if (!migration.Begin())
240 return false;
241
242 if (db_->Execute("DROP TABLE ItemTable")) {
243 CreateTableV2();
244 if (CommitChanges(false, values))
245 return migration.Commit();
246 }
247 return false;
248 }
249
250 void DomStorageDatabase::Close() {
251 db_.reset(NULL);
252 }
253
254 } // namespace dom_storage
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698