1 /*
2 * Copyright (C) 2011 Google Inc. All rights reserved.
3 * Copyright (C) 2013 Apple Inc. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15 * its contributors may be used to endorse or promote products derived
16 * from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30 #include "config.h"
31 #include "modules/webdatabase/DatabaseBackendBase.h"
32
33 #include "core/dom/ExceptionCode.h"
34 #include "core/dom/ExecutionContext.h"
35 #include "platform/Logging.h"
36 #include "modules/webdatabase/DatabaseAuthorizer.h"
37 #include "modules/webdatabase/DatabaseBase.h"
38 #include "modules/webdatabase/DatabaseContext.h"
39 #include "modules/webdatabase/DatabaseManager.h"
40 #include "modules/webdatabase/DatabaseTracker.h"
41 #include "modules/webdatabase/sqlite/SQLiteStatement.h"
42 #include "modules/webdatabase/sqlite/SQLiteTransaction.h"
43 #include "platform/weborigin/DatabaseIdentifier.h"
44 #include "public/platform/Platform.h"
45 #include "public/platform/WebDatabaseObserver.h"
46 #include "wtf/HashMap.h"
47 #include "wtf/HashSet.h"
48 #include "wtf/PassRefPtr.h"
49 #include "wtf/StdLibExtras.h"
50 #include "wtf/text/CString.h"
51 #include "wtf/text/StringHash.h"
52
53 // Registering "opened" databases with the DatabaseTracker
54 // =======================================================
55 // The DatabaseTracker maintains a list of databases that have been
56 // "opened" so that the client can call interrupt or delete on every database
57 // associated with a DatabaseContext.
58 //
59 // We will only call DatabaseTracker::addOpenDatabase() to add the database
60 // to the tracker as opened when we've succeeded in opening the database,
61 // and will set m_opened to true. Similarly, we only call
62 // DatabaseTracker::removeOpenDatabase() to remove the database from the
63 // tracker when we set m_opened to false in closeDatabase(). This sets up
64 // a simple symmetry between open and close operations, and a direct
65 // correlation to adding and removing databases from the tracker's list,
66 // thus ensuring that we have a correct list for the interrupt and
67 // delete operations to work on.
68 //
69 // The only databases instances not tracked by the tracker's open database
70 // list are the ones that have not been added yet, or the ones that we
71 // attempted an open on but failed to. Such instances only exist in the
72 // DatabaseServer's factory methods for creating database backends.
73 //
74 // The factory methods will either call openAndVerifyVersion() or
75 // performOpenAndVerify(). These methods will add the newly instantiated
76 // database backend if they succeed in opening the requested database.
77 // In the case of failure to open the database, the factory methods will
78 // simply discard the newly instantiated database backend when they return.
79 // The ref counting mechanims will automatically destruct the un-added
80 // (and un-returned) databases instances.
81
82 namespace WebCore {
83
84 static const char versionKey[] = "WebKitDatabaseVersionKey";
85 static const char infoTableName[] = "__WebKitDatabaseInfoTable__";
86
formatErrorMessage(const char * message,int sqliteErrorCode,const char * sqliteErrorMessage)87 static String formatErrorMessage(const char* message, int sqliteErrorCode, const char* sqliteErrorMessage)
88 {
89 return String::format("%s (%d %s)", message, sqliteErrorCode, sqliteErrorMessage);
90 }
91
retrieveTextResultFromDatabase(SQLiteDatabase & db,const String & query,String & resultString)92 static bool retrieveTextResultFromDatabase(SQLiteDatabase& db, const String& query, String& resultString)
93 {
94 SQLiteStatement statement(db, query);
95 int result = statement.prepare();
96
97 if (result != SQLResultOk) {
98 WTF_LOG_ERROR("Error (%i) preparing statement to read text result from database (%s)", result, query.ascii().data());
99 return false;
100 }
101
102 result = statement.step();
103 if (result == SQLResultRow) {
104 resultString = statement.getColumnText(0);
105 return true;
106 }
107 if (result == SQLResultDone) {
108 resultString = String();
109 return true;
110 }
111
112 WTF_LOG_ERROR("Error (%i) reading text result from database (%s)", result, query.ascii().data());
113 return false;
114 }
115
setTextValueInDatabase(SQLiteDatabase & db,const String & query,const String & value)116 static bool setTextValueInDatabase(SQLiteDatabase& db, const String& query, const String& value)
117 {
118 SQLiteStatement statement(db, query);
119 int result = statement.prepare();
120
121 if (result != SQLResultOk) {
122 WTF_LOG_ERROR("Failed to prepare statement to set value in database (%s)", query.ascii().data());
123 return false;
124 }
125
126 statement.bindText(1, value);
127
128 result = statement.step();
129 if (result != SQLResultDone) {
130 WTF_LOG_ERROR("Failed to step statement to set value in database (%s)", query.ascii().data());
131 return false;
132 }
133
134 return true;
135 }
136
137 // FIXME: move all guid-related functions to a DatabaseVersionTracker class.
guidMutex()138 static Mutex& guidMutex()
139 {
140 AtomicallyInitializedStatic(Mutex&, mutex = *new Mutex);
141 return mutex;
142 }
143
144 typedef HashMap<DatabaseGuid, String> GuidVersionMap;
guidToVersionMap()145 static GuidVersionMap& guidToVersionMap()
146 {
147 // Ensure the the mutex is locked.
148 ASSERT(!guidMutex().tryLock());
149 DEFINE_STATIC_LOCAL(GuidVersionMap, map, ());
150 return map;
151 }
152
153 // NOTE: Caller must lock guidMutex().
updateGuidVersionMap(DatabaseGuid guid,String newVersion)154 static inline void updateGuidVersionMap(DatabaseGuid guid, String newVersion)
155 {
156 // Ensure the the mutex is locked.
157 ASSERT(!guidMutex().tryLock());
158
159 // Note: It is not safe to put an empty string into the guidToVersionMap() map.
160 // That's because the map is cross-thread, but empty strings are per-thread.
161 // The copy() function makes a version of the string you can use on the current
162 // thread, but we need a string we can keep in a cross-thread data structure.
163 // FIXME: This is a quite-awkward restriction to have to program with.
164
165 // Map null string to empty string (see comment above).
166 guidToVersionMap().set(guid, newVersion.isEmpty() ? String() : newVersion.isolatedCopy());
167 }
168
169 typedef HashMap<DatabaseGuid, HashSet<DatabaseBackendBase*>*> GuidDatabaseMap;
guidToDatabaseMap()170 static GuidDatabaseMap& guidToDatabaseMap()
171 {
172 // Ensure the the mutex is locked.
173 ASSERT(!guidMutex().tryLock());
174 DEFINE_STATIC_LOCAL(GuidDatabaseMap, map, ());
175 return map;
176 }
177
guidForOriginAndName(const String & origin,const String & name)178 static DatabaseGuid guidForOriginAndName(const String& origin, const String& name)
179 {
180 // Ensure the the mutex is locked.
181 ASSERT(!guidMutex().tryLock());
182
183 String stringID = origin + "/" + name;
184
185 typedef HashMap<String, int> IDGuidMap;
186 DEFINE_STATIC_LOCAL(IDGuidMap, stringIdentifierToGUIDMap, ());
187 DatabaseGuid guid = stringIdentifierToGUIDMap.get(stringID);
188 if (!guid) {
189 static int currentNewGUID = 1;
190 guid = currentNewGUID++;
191 stringIdentifierToGUIDMap.set(stringID, guid);
192 }
193
194 return guid;
195 }
196
197 // static
databaseInfoTableName()198 const char* DatabaseBackendBase::databaseInfoTableName()
199 {
200 return infoTableName;
201 }
202
DatabaseBackendBase(DatabaseContext * databaseContext,const String & name,const String & expectedVersion,const String & displayName,unsigned long estimatedSize,DatabaseType databaseType)203 DatabaseBackendBase::DatabaseBackendBase(DatabaseContext* databaseContext, const String& name,
204 const String& expectedVersion, const String& displayName, unsigned long estimatedSize, DatabaseType databaseType)
205 : m_databaseContext(databaseContext)
206 , m_name(name.isolatedCopy())
207 , m_expectedVersion(expectedVersion.isolatedCopy())
208 , m_displayName(displayName.isolatedCopy())
209 , m_estimatedSize(estimatedSize)
210 , m_guid(0)
211 , m_opened(false)
212 , m_new(false)
213 , m_isSyncDatabase(databaseType == DatabaseType::Sync)
214 {
215 m_contextThreadSecurityOrigin = m_databaseContext->securityOrigin()->isolatedCopy();
216
217 m_databaseAuthorizer = DatabaseAuthorizer::create(infoTableName);
218
219 if (m_name.isNull())
220 m_name = "";
221
222 {
223 SafePointAwareMutexLocker locker(guidMutex());
224 m_guid = guidForOriginAndName(securityOrigin()->toString(), name);
225 HashSet<DatabaseBackendBase*>* hashSet = guidToDatabaseMap().get(m_guid);
226 if (!hashSet) {
227 hashSet = new HashSet<DatabaseBackendBase*>;
228 guidToDatabaseMap().set(m_guid, hashSet);
229 }
230
231 hashSet->add(this);
232 }
233
234 m_filename = DatabaseManager::manager().fullPathForDatabase(securityOrigin(), m_name);
235 }
236
~DatabaseBackendBase()237 DatabaseBackendBase::~DatabaseBackendBase()
238 {
239 // SQLite is "multi-thread safe", but each database handle can only be used
240 // on a single thread at a time.
241 //
242 // For DatabaseBackend, we open the SQLite database on the DatabaseThread,
243 // and hence we should also close it on that same thread. This means that the
244 // SQLite database need to be closed by another mechanism (see
245 // DatabaseContext::stopDatabases()). By the time we get here, the SQLite
246 // database should have already been closed.
247
248 ASSERT(!m_opened);
249 }
250
trace(Visitor * visitor)251 void DatabaseBackendBase::trace(Visitor* visitor)
252 {
253 visitor->trace(m_databaseContext);
254 visitor->trace(m_sqliteDatabase);
255 visitor->trace(m_databaseAuthorizer);
256 }
257
closeDatabase()258 void DatabaseBackendBase::closeDatabase()
259 {
260 if (!m_opened)
261 return;
262
263 m_sqliteDatabase.close();
264 m_opened = false;
265 databaseContext()->didCloseDatabase(*this);
266 // See comment at the top this file regarding calling removeOpenDatabase().
267 DatabaseTracker::tracker().removeOpenDatabase(this);
268 {
269 SafePointAwareMutexLocker locker(guidMutex());
270
271 HashSet<DatabaseBackendBase*>* hashSet = guidToDatabaseMap().get(m_guid);
272 ASSERT(hashSet);
273 ASSERT(hashSet->contains(this));
274 hashSet->remove(this);
275 if (hashSet->isEmpty()) {
276 guidToDatabaseMap().remove(m_guid);
277 delete hashSet;
278 guidToVersionMap().remove(m_guid);
279 }
280 }
281 }
282
version() const283 String DatabaseBackendBase::version() const
284 {
285 // Note: In multi-process browsers the cached value may be accurate, but we cannot read the
286 // actual version from the database without potentially inducing a deadlock.
287 // FIXME: Add an async version getter to the DatabaseAPI.
288 return getCachedVersion();
289 }
290
291 class DoneCreatingDatabaseOnExitCaller {
292 public:
DoneCreatingDatabaseOnExitCaller(DatabaseBackendBase * database)293 DoneCreatingDatabaseOnExitCaller(DatabaseBackendBase* database)
294 : m_database(database)
295 , m_openSucceeded(false)
296 {
297 }
~DoneCreatingDatabaseOnExitCaller()298 ~DoneCreatingDatabaseOnExitCaller()
299 {
300 if (!m_openSucceeded)
301 DatabaseTracker::tracker().failedToOpenDatabase(m_database);
302 }
303
setOpenSucceeded()304 void setOpenSucceeded() { m_openSucceeded = true; }
305
306 private:
307 DatabaseBackendBase* m_database;
308 bool m_openSucceeded;
309 };
310
performOpenAndVerify(bool shouldSetVersionInNewDatabase,DatabaseError & error,String & errorMessage)311 bool DatabaseBackendBase::performOpenAndVerify(bool shouldSetVersionInNewDatabase, DatabaseError& error, String& errorMessage)
312 {
313 DoneCreatingDatabaseOnExitCaller onExitCaller(this);
314 ASSERT(errorMessage.isEmpty());
315 ASSERT(error == DatabaseError::None); // Better not have any errors already.
316 error = DatabaseError::InvalidDatabaseState; // Presumed failure. We'll clear it if we succeed below.
317
318 const int maxSqliteBusyWaitTime = 30000;
319
320 if (!m_sqliteDatabase.open(m_filename, true)) {
321 reportOpenDatabaseResult(1, InvalidStateError, m_sqliteDatabase.lastError());
322 errorMessage = formatErrorMessage("unable to open database", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
323 return false;
324 }
325 if (!m_sqliteDatabase.turnOnIncrementalAutoVacuum())
326 WTF_LOG_ERROR("Unable to turn on incremental auto-vacuum (%d %s)", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
327
328 m_sqliteDatabase.setBusyTimeout(maxSqliteBusyWaitTime);
329
330 String currentVersion;
331 {
332 SafePointAwareMutexLocker locker(guidMutex());
333
334 GuidVersionMap::iterator entry = guidToVersionMap().find(m_guid);
335 if (entry != guidToVersionMap().end()) {
336 // Map null string to empty string (see updateGuidVersionMap()).
337 currentVersion = entry->value.isNull() ? emptyString() : entry->value.isolatedCopy();
338 WTF_LOG(StorageAPI, "Current cached version for guid %i is %s", m_guid, currentVersion.ascii().data());
339
340 // Note: In multi-process browsers the cached value may be inaccurate, but
341 // we cannot read the actual version from the database without potentially
342 // inducing a form of deadlock, a busytimeout error when trying to
343 // access the database. So we'll use the cached value if we're unable to read
344 // the value from the database file without waiting.
345 // FIXME: Add an async openDatabase method to the DatabaseAPI.
346 const int noSqliteBusyWaitTime = 0;
347 m_sqliteDatabase.setBusyTimeout(noSqliteBusyWaitTime);
348 String versionFromDatabase;
349 if (getVersionFromDatabase(versionFromDatabase, false)) {
350 currentVersion = versionFromDatabase;
351 updateGuidVersionMap(m_guid, currentVersion);
352 }
353 m_sqliteDatabase.setBusyTimeout(maxSqliteBusyWaitTime);
354 } else {
355 WTF_LOG(StorageAPI, "No cached version for guid %i", m_guid);
356
357 SQLiteTransaction transaction(m_sqliteDatabase);
358 transaction.begin();
359 if (!transaction.inProgress()) {
360 reportOpenDatabaseResult(2, InvalidStateError, m_sqliteDatabase.lastError());
361 errorMessage = formatErrorMessage("unable to open database, failed to start transaction", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
362 m_sqliteDatabase.close();
363 return false;
364 }
365
366 String tableName(infoTableName);
367 if (!m_sqliteDatabase.tableExists(tableName)) {
368 m_new = true;
369
370 if (!m_sqliteDatabase.executeCommand("CREATE TABLE " + tableName + " (key TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT REPLACE,value TEXT NOT NULL ON CONFLICT FAIL);")) {
371 reportOpenDatabaseResult(3, InvalidStateError, m_sqliteDatabase.lastError());
372 errorMessage = formatErrorMessage("unable to open database, failed to create 'info' table", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
373 transaction.rollback();
374 m_sqliteDatabase.close();
375 return false;
376 }
377 } else if (!getVersionFromDatabase(currentVersion, false)) {
378 reportOpenDatabaseResult(4, InvalidStateError, m_sqliteDatabase.lastError());
379 errorMessage = formatErrorMessage("unable to open database, failed to read current version", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
380 transaction.rollback();
381 m_sqliteDatabase.close();
382 return false;
383 }
384
385 if (currentVersion.length()) {
386 WTF_LOG(StorageAPI, "Retrieved current version %s from database %s", currentVersion.ascii().data(), databaseDebugName().ascii().data());
387 } else if (!m_new || shouldSetVersionInNewDatabase) {
388 WTF_LOG(StorageAPI, "Setting version %s in database %s that was just created", m_expectedVersion.ascii().data(), databaseDebugName().ascii().data());
389 if (!setVersionInDatabase(m_expectedVersion, false)) {
390 reportOpenDatabaseResult(5, InvalidStateError, m_sqliteDatabase.lastError());
391 errorMessage = formatErrorMessage("unable to open database, failed to write current version", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
392 transaction.rollback();
393 m_sqliteDatabase.close();
394 return false;
395 }
396 currentVersion = m_expectedVersion;
397 }
398 updateGuidVersionMap(m_guid, currentVersion);
399 transaction.commit();
400 }
401 }
402
403 if (currentVersion.isNull()) {
404 WTF_LOG(StorageAPI, "Database %s does not have its version set", databaseDebugName().ascii().data());
405 currentVersion = "";
406 }
407
408 // If the expected version isn't the empty string, ensure that the current database version we have matches that version. Otherwise, set an exception.
409 // If the expected version is the empty string, then we always return with whatever version of the database we have.
410 if ((!m_new || shouldSetVersionInNewDatabase) && m_expectedVersion.length() && m_expectedVersion != currentVersion) {
411 reportOpenDatabaseResult(6, InvalidStateError, 0);
412 errorMessage = "unable to open database, version mismatch, '" + m_expectedVersion + "' does not match the currentVersion of '" + currentVersion + "'";
413 m_sqliteDatabase.close();
414 return false;
415 }
416
417 ASSERT(m_databaseAuthorizer);
418 m_sqliteDatabase.setAuthorizer(m_databaseAuthorizer.get());
419
420 databaseContext()->didOpenDatabase(*this);
421 // See comment at the top this file regarding calling addOpenDatabase().
422 DatabaseTracker::tracker().addOpenDatabase(this);
423 m_opened = true;
424
425 // Declare success:
426 error = DatabaseError::None; // Clear the presumed error from above.
427 onExitCaller.setOpenSucceeded();
428
429 if (m_new && !shouldSetVersionInNewDatabase)
430 m_expectedVersion = ""; // The caller provided a creationCallback which will set the expected version.
431
432 reportOpenDatabaseResult(0, -1, 0); // OK
433 return true;
434 }
435
securityOrigin() const436 SecurityOrigin* DatabaseBackendBase::securityOrigin() const
437 {
438 return m_contextThreadSecurityOrigin.get();
439 }
440
stringIdentifier() const441 String DatabaseBackendBase::stringIdentifier() const
442 {
443 // Return a deep copy for ref counting thread safety
444 return m_name.isolatedCopy();
445 }
446
displayName() const447 String DatabaseBackendBase::displayName() const
448 {
449 // Return a deep copy for ref counting thread safety
450 return m_displayName.isolatedCopy();
451 }
452
estimatedSize() const453 unsigned long DatabaseBackendBase::estimatedSize() const
454 {
455 return m_estimatedSize;
456 }
457
fileName() const458 String DatabaseBackendBase::fileName() const
459 {
460 // Return a deep copy for ref counting thread safety
461 return m_filename.isolatedCopy();
462 }
463
getVersionFromDatabase(String & version,bool shouldCacheVersion)464 bool DatabaseBackendBase::getVersionFromDatabase(String& version, bool shouldCacheVersion)
465 {
466 String query(String("SELECT value FROM ") + infoTableName + " WHERE key = '" + versionKey + "';");
467
468 m_databaseAuthorizer->disable();
469
470 bool result = retrieveTextResultFromDatabase(m_sqliteDatabase, query, version);
471 if (result) {
472 if (shouldCacheVersion)
473 setCachedVersion(version);
474 } else
475 WTF_LOG_ERROR("Failed to retrieve version from database %s", databaseDebugName().ascii().data());
476
477 m_databaseAuthorizer->enable();
478
479 return result;
480 }
481
setVersionInDatabase(const String & version,bool shouldCacheVersion)482 bool DatabaseBackendBase::setVersionInDatabase(const String& version, bool shouldCacheVersion)
483 {
484 // The INSERT will replace an existing entry for the database with the new version number, due to the UNIQUE ON CONFLICT REPLACE
485 // clause in the CREATE statement (see Database::performOpenAndVerify()).
486 String query(String("INSERT INTO ") + infoTableName + " (key, value) VALUES ('" + versionKey + "', ?);");
487
488 m_databaseAuthorizer->disable();
489
490 bool result = setTextValueInDatabase(m_sqliteDatabase, query, version);
491 if (result) {
492 if (shouldCacheVersion)
493 setCachedVersion(version);
494 } else
495 WTF_LOG_ERROR("Failed to set version %s in database (%s)", version.ascii().data(), query.ascii().data());
496
497 m_databaseAuthorizer->enable();
498
499 return result;
500 }
501
setExpectedVersion(const String & version)502 void DatabaseBackendBase::setExpectedVersion(const String& version)
503 {
504 m_expectedVersion = version.isolatedCopy();
505 }
506
getCachedVersion() const507 String DatabaseBackendBase::getCachedVersion() const
508 {
509 SafePointAwareMutexLocker locker(guidMutex());
510 return guidToVersionMap().get(m_guid).isolatedCopy();
511 }
512
setCachedVersion(const String & actualVersion)513 void DatabaseBackendBase::setCachedVersion(const String& actualVersion)
514 {
515 // Update the in memory database version map.
516 SafePointAwareMutexLocker locker(guidMutex());
517 updateGuidVersionMap(m_guid, actualVersion);
518 }
519
getActualVersionForTransaction(String & actualVersion)520 bool DatabaseBackendBase::getActualVersionForTransaction(String &actualVersion)
521 {
522 ASSERT(m_sqliteDatabase.transactionInProgress());
523 // Note: In multi-process browsers the cached value may be inaccurate.
524 // So we retrieve the value from the database and update the cached value here.
525 return getVersionFromDatabase(actualVersion, true);
526 }
527
disableAuthorizer()528 void DatabaseBackendBase::disableAuthorizer()
529 {
530 ASSERT(m_databaseAuthorizer);
531 m_databaseAuthorizer->disable();
532 }
533
enableAuthorizer()534 void DatabaseBackendBase::enableAuthorizer()
535 {
536 ASSERT(m_databaseAuthorizer);
537 m_databaseAuthorizer->enable();
538 }
539
setAuthorizerPermissions(int permissions)540 void DatabaseBackendBase::setAuthorizerPermissions(int permissions)
541 {
542 ASSERT(m_databaseAuthorizer);
543 m_databaseAuthorizer->setPermissions(permissions);
544 }
545
lastActionChangedDatabase()546 bool DatabaseBackendBase::lastActionChangedDatabase()
547 {
548 ASSERT(m_databaseAuthorizer);
549 return m_databaseAuthorizer->lastActionChangedDatabase();
550 }
551
lastActionWasInsert()552 bool DatabaseBackendBase::lastActionWasInsert()
553 {
554 ASSERT(m_databaseAuthorizer);
555 return m_databaseAuthorizer->lastActionWasInsert();
556 }
557
resetDeletes()558 void DatabaseBackendBase::resetDeletes()
559 {
560 ASSERT(m_databaseAuthorizer);
561 m_databaseAuthorizer->resetDeletes();
562 }
563
hadDeletes()564 bool DatabaseBackendBase::hadDeletes()
565 {
566 ASSERT(m_databaseAuthorizer);
567 return m_databaseAuthorizer->hadDeletes();
568 }
569
resetAuthorizer()570 void DatabaseBackendBase::resetAuthorizer()
571 {
572 if (m_databaseAuthorizer)
573 m_databaseAuthorizer->reset();
574 }
575
maximumSize() const576 unsigned long long DatabaseBackendBase::maximumSize() const
577 {
578 return DatabaseTracker::tracker().getMaxSizeForDatabase(this);
579 }
580
incrementalVacuumIfNeeded()581 void DatabaseBackendBase::incrementalVacuumIfNeeded()
582 {
583 int64_t freeSpaceSize = m_sqliteDatabase.freeSpaceSize();
584 int64_t totalSize = m_sqliteDatabase.totalSize();
585 if (totalSize <= 10 * freeSpaceSize) {
586 int result = m_sqliteDatabase.runIncrementalVacuumCommand();
587 reportVacuumDatabaseResult(result);
588 if (result != SQLResultOk)
589 logErrorMessage(formatErrorMessage("error vacuuming database", result, m_sqliteDatabase.lastErrorMsg()));
590 }
591 }
592
interrupt()593 void DatabaseBackendBase::interrupt()
594 {
595 m_sqliteDatabase.interrupt();
596 }
597
isInterrupted()598 bool DatabaseBackendBase::isInterrupted()
599 {
600 MutexLocker locker(m_sqliteDatabase.databaseMutex());
601 return m_sqliteDatabase.isInterrupted();
602 }
603
604 // These are used to generate histograms of errors seen with websql.
605 // See about:histograms in chromium.
reportOpenDatabaseResult(int errorSite,int webSqlErrorCode,int sqliteErrorCode)606 void DatabaseBackendBase::reportOpenDatabaseResult(int errorSite, int webSqlErrorCode, int sqliteErrorCode)
607 {
608 if (blink::Platform::current()->databaseObserver()) {
609 blink::Platform::current()->databaseObserver()->reportOpenDatabaseResult(
610 createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
611 stringIdentifier(), isSyncDatabase(),
612 errorSite, webSqlErrorCode, sqliteErrorCode);
613 }
614 }
615
reportChangeVersionResult(int errorSite,int webSqlErrorCode,int sqliteErrorCode)616 void DatabaseBackendBase::reportChangeVersionResult(int errorSite, int webSqlErrorCode, int sqliteErrorCode)
617 {
618 if (blink::Platform::current()->databaseObserver()) {
619 blink::Platform::current()->databaseObserver()->reportChangeVersionResult(
620 createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
621 stringIdentifier(), isSyncDatabase(),
622 errorSite, webSqlErrorCode, sqliteErrorCode);
623 }
624 }
625
reportStartTransactionResult(int errorSite,int webSqlErrorCode,int sqliteErrorCode)626 void DatabaseBackendBase::reportStartTransactionResult(int errorSite, int webSqlErrorCode, int sqliteErrorCode)
627 {
628 if (blink::Platform::current()->databaseObserver()) {
629 blink::Platform::current()->databaseObserver()->reportStartTransactionResult(
630 createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
631 stringIdentifier(), isSyncDatabase(),
632 errorSite, webSqlErrorCode, sqliteErrorCode);
633 }
634 }
635
reportCommitTransactionResult(int errorSite,int webSqlErrorCode,int sqliteErrorCode)636 void DatabaseBackendBase::reportCommitTransactionResult(int errorSite, int webSqlErrorCode, int sqliteErrorCode)
637 {
638 if (blink::Platform::current()->databaseObserver()) {
639 blink::Platform::current()->databaseObserver()->reportCommitTransactionResult(
640 createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
641 stringIdentifier(), isSyncDatabase(),
642 errorSite, webSqlErrorCode, sqliteErrorCode);
643 }
644 }
645
reportExecuteStatementResult(int errorSite,int webSqlErrorCode,int sqliteErrorCode)646 void DatabaseBackendBase::reportExecuteStatementResult(int errorSite, int webSqlErrorCode, int sqliteErrorCode)
647 {
648 if (blink::Platform::current()->databaseObserver()) {
649 blink::Platform::current()->databaseObserver()->reportExecuteStatementResult(
650 createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
651 stringIdentifier(), isSyncDatabase(),
652 errorSite, webSqlErrorCode, sqliteErrorCode);
653 }
654 }
655
reportVacuumDatabaseResult(int sqliteErrorCode)656 void DatabaseBackendBase::reportVacuumDatabaseResult(int sqliteErrorCode)
657 {
658 if (blink::Platform::current()->databaseObserver()) {
659 blink::Platform::current()->databaseObserver()->reportVacuumDatabaseResult(
660 createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
661 stringIdentifier(), isSyncDatabase(), sqliteErrorCode);
662 }
663 }
664
logErrorMessage(const String & message)665 void DatabaseBackendBase::logErrorMessage(const String& message)
666 {
667 executionContext()->addConsoleMessage(StorageMessageSource, ErrorMessageLevel, message);
668 }
669
executionContext() const670 ExecutionContext* DatabaseBackendBase::executionContext() const
671 {
672 return databaseContext()->executionContext();
673 }
674
675 } // namespace WebCore
676