2 * Copyright (C) 2011 Google Inc. All rights reserved.
3 * Copyright (C) 2013 Apple Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
31 #include "DatabaseBackendBase.h"
33 #if ENABLE(SQL_DATABASE)
35 #include "DatabaseAuthorizer.h"
36 #include "DatabaseBackendContext.h"
37 #include "DatabaseBase.h"
38 #include "DatabaseContext.h"
39 #include "DatabaseManager.h"
40 #include "DatabaseTracker.h"
41 #include "ExceptionCode.h"
43 #include "SQLiteStatement.h"
44 #include "SQLiteTransaction.h"
45 #include "SecurityOrigin.h"
46 #include <wtf/HashMap.h>
47 #include <wtf/HashSet.h>
48 #include <wtf/NeverDestroyed.h>
49 #include <wtf/PassRefPtr.h>
50 #include <wtf/RefPtr.h>
51 #include <wtf/StdLibExtras.h>
52 #include <wtf/text/CString.h>
53 #include <wtf/text/StringHash.h>
56 #include "SQLiteDatabaseTracker.h"
59 // Registering "opened" databases with the DatabaseTracker
60 // =======================================================
61 // The DatabaseTracker maintains a list of databases that have been
62 // "opened" so that the client can call interrupt or delete on every database
63 // associated with a DatabaseBackendContext.
65 // We will only call DatabaseTracker::addOpenDatabase() to add the database
66 // to the tracker as opened when we've succeeded in opening the database,
67 // and will set m_opened to true. Similarly, we only call
68 // DatabaseTracker::removeOpenDatabase() to remove the database from the
69 // tracker when we set m_opened to false in closeDatabase(). This sets up
70 // a simple symmetry between open and close operations, and a direct
71 // correlation to adding and removing databases from the tracker's list,
72 // thus ensuring that we have a correct list for the interrupt and
73 // delete operations to work on.
75 // The only databases instances not tracked by the tracker's open database
76 // list are the ones that have not been added yet, or the ones that we
77 // attempted an open on but failed to. Such instances only exist in the
78 // DatabaseServer's factory methods for creating database backends.
80 // The factory methods will either call openAndVerifyVersion() or
81 // performOpenAndVerify(). These methods will add the newly instantiated
82 // database backend if they succeed in opening the requested database.
83 // In the case of failure to open the database, the factory methods will
84 // simply discard the newly instantiated database backend when they return.
85 // The ref counting mechanims will automatically destruct the un-added
86 // (and un-returned) databases instances.
90 static const char versionKey[] = "WebKitDatabaseVersionKey";
91 static const char infoTableName[] = "__WebKitDatabaseInfoTable__";
93 static String formatErrorMessage(const char* message, int sqliteErrorCode, const char* sqliteErrorMessage)
95 return String::format("%s (%d %s)", message, sqliteErrorCode, sqliteErrorMessage);
98 static bool retrieveTextResultFromDatabase(SQLiteDatabase& db, const String& query, String& resultString)
100 SQLiteStatement statement(db, query);
101 int result = statement.prepare();
103 if (result != SQLResultOk) {
104 LOG_ERROR("Error (%i) preparing statement to read text result from database (%s)", result, query.ascii().data());
108 result = statement.step();
109 if (result == SQLResultRow) {
110 resultString = statement.getColumnText(0);
113 if (result == SQLResultDone) {
114 resultString = String();
118 LOG_ERROR("Error (%i) reading text result from database (%s)", result, query.ascii().data());
122 static bool setTextValueInDatabase(SQLiteDatabase& db, const String& query, const String& value)
124 SQLiteStatement statement(db, query);
125 int result = statement.prepare();
127 if (result != SQLResultOk) {
128 LOG_ERROR("Failed to prepare statement to set value in database (%s)", query.ascii().data());
132 statement.bindText(1, value);
134 result = statement.step();
135 if (result != SQLResultDone) {
136 LOG_ERROR("Failed to step statement to set value in database (%s)", query.ascii().data());
143 // FIXME: move all guid-related functions to a DatabaseVersionTracker class.
144 static Mutex& guidMutex()
146 AtomicallyInitializedStatic(Mutex&, mutex = *new Mutex);
150 typedef HashMap<DatabaseGuid, String> GuidVersionMap;
151 static GuidVersionMap& guidToVersionMap()
153 // Ensure the the mutex is locked.
154 ASSERT(!guidMutex().tryLock());
155 DEFINE_STATIC_LOCAL(GuidVersionMap, map, ());
159 // NOTE: Caller must lock guidMutex().
160 static inline void updateGuidVersionMap(DatabaseGuid guid, String newVersion)
162 // Ensure the the mutex is locked.
163 ASSERT(!guidMutex().tryLock());
165 // Note: It is not safe to put an empty string into the guidToVersionMap() map.
166 // That's because the map is cross-thread, but empty strings are per-thread.
167 // The copy() function makes a version of the string you can use on the current
168 // thread, but we need a string we can keep in a cross-thread data structure.
169 // FIXME: This is a quite-awkward restriction to have to program with.
171 // Map null string to empty string (see comment above).
172 guidToVersionMap().set(guid, newVersion.isEmpty() ? String() : newVersion.isolatedCopy());
175 typedef HashMap<DatabaseGuid, std::unique_ptr<HashSet<DatabaseBackendBase*>>> GuidDatabaseMap;
177 static GuidDatabaseMap& guidToDatabaseMap()
179 // Ensure the the mutex is locked.
180 ASSERT(!guidMutex().tryLock());
181 static NeverDestroyed<GuidDatabaseMap> map;
185 static DatabaseGuid guidForOriginAndName(const String& origin, const String& name)
187 // Ensure the the mutex is locked.
188 ASSERT(!guidMutex().tryLock());
190 String stringID = origin + "/" + name;
192 typedef HashMap<String, int> IDGuidMap;
193 static NeverDestroyed<HashMap<String, int>> map;
194 DatabaseGuid guid = map.get().get(stringID);
196 static int currentNewGUID = 1;
197 guid = currentNewGUID++;
198 map.get().set(stringID, guid);
205 const char* DatabaseBackendBase::databaseInfoTableName()
207 return infoTableName;
210 #if !LOG_DISABLED || !ERROR_DISABLED
211 String DatabaseBackendBase::databaseDebugName() const
213 return m_contextThreadSecurityOrigin->toString() + "::" + m_name;
217 DatabaseBackendBase::DatabaseBackendBase(PassRefPtr<DatabaseBackendContext> databaseContext, const String& name,
218 const String& expectedVersion, const String& displayName, unsigned long estimatedSize, DatabaseType databaseType)
219 : m_databaseContext(databaseContext)
220 , m_name(name.isolatedCopy())
221 , m_expectedVersion(expectedVersion.isolatedCopy())
222 , m_displayName(displayName.isolatedCopy())
223 , m_estimatedSize(estimatedSize)
226 , m_isSyncDatabase(databaseType == DatabaseType::Sync)
228 m_contextThreadSecurityOrigin = m_databaseContext->securityOrigin()->isolatedCopy();
230 m_databaseAuthorizer = DatabaseAuthorizer::create(infoTableName);
233 m_name = emptyString();
236 MutexLocker locker(guidMutex());
237 m_guid = guidForOriginAndName(securityOrigin()->toString(), name);
238 std::unique_ptr<HashSet<DatabaseBackendBase*>>& hashSet = guidToDatabaseMap().add(m_guid, nullptr).iterator->value;
240 hashSet = std::make_unique<HashSet<DatabaseBackendBase*>>();
244 m_filename = DatabaseManager::manager().fullPathForDatabase(securityOrigin(), m_name);
247 DatabaseBackendBase::~DatabaseBackendBase()
249 // SQLite is "multi-thread safe", but each database handle can only be used
250 // on a single thread at a time.
252 // For DatabaseBackend, we open the SQLite database on the DatabaseThread,
253 // and hence we should also close it on that same thread. This means that the
254 // SQLite database need to be closed by another mechanism (see
255 // DatabaseContext::stopDatabases()). By the time we get here, the SQLite
256 // database should have already been closed.
261 void DatabaseBackendBase::closeDatabase()
266 m_sqliteDatabase.close();
268 // See comment at the top this file regarding calling removeOpenDatabase().
269 DatabaseTracker::tracker().removeOpenDatabase(this);
271 MutexLocker locker(guidMutex());
273 auto it = guidToDatabaseMap().find(m_guid);
274 ASSERT(it != guidToDatabaseMap().end());
276 ASSERT(it->value->contains(this));
277 it->value->remove(this);
278 if (it->value->isEmpty()) {
279 guidToDatabaseMap().remove(it);
280 guidToVersionMap().remove(m_guid);
285 String DatabaseBackendBase::version() const
287 // Note: In multi-process browsers the cached value may be accurate, but we cannot read the
288 // actual version from the database without potentially inducing a deadlock.
289 // FIXME: Add an async version getter to the DatabaseAPI.
290 return getCachedVersion();
293 class DoneCreatingDatabaseOnExitCaller {
295 DoneCreatingDatabaseOnExitCaller(DatabaseBackendBase* database)
296 : m_database(database)
297 , m_openSucceeded(false)
300 ~DoneCreatingDatabaseOnExitCaller()
302 DatabaseTracker::tracker().doneCreatingDatabase(m_database);
305 void setOpenSucceeded() { m_openSucceeded = true; }
308 DatabaseBackendBase* m_database;
309 bool m_openSucceeded;
312 bool DatabaseBackendBase::performOpenAndVerify(bool shouldSetVersionInNewDatabase, DatabaseError& error, String& errorMessage)
314 DoneCreatingDatabaseOnExitCaller onExitCaller(this);
315 ASSERT(errorMessage.isEmpty());
316 ASSERT(error == DatabaseError::None); // Better not have any errors already.
317 error = DatabaseError::InvalidDatabaseState; // Presumed failure. We'll clear it if we succeed below.
319 const int maxSqliteBusyWaitTime = 30000;
323 // Make sure we wait till the background removal of the empty database files finished before trying to open any database.
324 MutexLocker locker(DatabaseTracker::openDatabaseMutex());
326 SQLiteTransactionInProgressAutoCounter transactionCounter;
329 if (!m_sqliteDatabase.open(m_filename, true)) {
330 errorMessage = formatErrorMessage("unable to open database", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
333 if (!m_sqliteDatabase.turnOnIncrementalAutoVacuum())
334 LOG_ERROR("Unable to turn on incremental auto-vacuum (%d %s)", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
336 m_sqliteDatabase.setBusyTimeout(maxSqliteBusyWaitTime);
338 String currentVersion;
340 MutexLocker locker(guidMutex());
342 auto entry = guidToVersionMap().find(m_guid);
343 if (entry != guidToVersionMap().end()) {
344 // Map null string to empty string (see updateGuidVersionMap()).
345 currentVersion = entry->value.isNull() ? emptyString() : entry->value.isolatedCopy();
346 LOG(StorageAPI, "Current cached version for guid %i is %s", m_guid, currentVersion.ascii().data());
348 LOG(StorageAPI, "No cached version for guid %i", m_guid);
350 SQLiteTransaction transaction(m_sqliteDatabase);
352 if (!transaction.inProgress()) {
353 errorMessage = formatErrorMessage("unable to open database, failed to start transaction", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
354 m_sqliteDatabase.close();
358 String tableName(infoTableName);
359 if (!m_sqliteDatabase.tableExists(tableName)) {
362 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);")) {
363 errorMessage = formatErrorMessage("unable to open database, failed to create 'info' table", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
364 transaction.rollback();
365 m_sqliteDatabase.close();
368 } else if (!getVersionFromDatabase(currentVersion, false)) {
369 errorMessage = formatErrorMessage("unable to open database, failed to read current version", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
370 transaction.rollback();
371 m_sqliteDatabase.close();
375 if (currentVersion.length()) {
376 LOG(StorageAPI, "Retrieved current version %s from database %s", currentVersion.ascii().data(), databaseDebugName().ascii().data());
377 } else if (!m_new || shouldSetVersionInNewDatabase) {
378 LOG(StorageAPI, "Setting version %s in database %s that was just created", m_expectedVersion.ascii().data(), databaseDebugName().ascii().data());
379 if (!setVersionInDatabase(m_expectedVersion, false)) {
380 errorMessage = formatErrorMessage("unable to open database, failed to write current version", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
381 transaction.rollback();
382 m_sqliteDatabase.close();
385 currentVersion = m_expectedVersion;
387 updateGuidVersionMap(m_guid, currentVersion);
388 transaction.commit();
392 if (currentVersion.isNull()) {
393 LOG(StorageAPI, "Database %s does not have its version set", databaseDebugName().ascii().data());
397 // If the expected version isn't the empty string, ensure that the current database version we have matches that version. Otherwise, set an exception.
398 // If the expected version is the empty string, then we always return with whatever version of the database we have.
399 if ((!m_new || shouldSetVersionInNewDatabase) && m_expectedVersion.length() && m_expectedVersion != currentVersion) {
400 errorMessage = "unable to open database, version mismatch, '" + m_expectedVersion + "' does not match the currentVersion of '" + currentVersion + "'";
401 m_sqliteDatabase.close();
405 ASSERT(m_databaseAuthorizer);
406 m_sqliteDatabase.setAuthorizer(m_databaseAuthorizer);
408 // See comment at the top this file regarding calling addOpenDatabase().
409 DatabaseTracker::tracker().addOpenDatabase(this);
413 error = DatabaseError::None; // Clear the presumed error from above.
414 onExitCaller.setOpenSucceeded();
416 if (m_new && !shouldSetVersionInNewDatabase)
417 m_expectedVersion = ""; // The caller provided a creationCallback which will set the expected version.
421 SecurityOrigin* DatabaseBackendBase::securityOrigin() const
423 return m_contextThreadSecurityOrigin.get();
426 String DatabaseBackendBase::stringIdentifier() const
428 // Return a deep copy for ref counting thread safety
429 return m_name.isolatedCopy();
432 String DatabaseBackendBase::displayName() const
434 // Return a deep copy for ref counting thread safety
435 return m_displayName.isolatedCopy();
438 unsigned long DatabaseBackendBase::estimatedSize() const
440 return m_estimatedSize;
443 String DatabaseBackendBase::fileName() const
445 // Return a deep copy for ref counting thread safety
446 return m_filename.isolatedCopy();
449 DatabaseDetails DatabaseBackendBase::details() const
451 return DatabaseDetails(stringIdentifier(), displayName(), estimatedSize(), 0);
454 bool DatabaseBackendBase::getVersionFromDatabase(String& version, bool shouldCacheVersion)
456 String query(String("SELECT value FROM ") + infoTableName + " WHERE key = '" + versionKey + "';");
458 m_databaseAuthorizer->disable();
460 bool result = retrieveTextResultFromDatabase(m_sqliteDatabase, query, version);
462 if (shouldCacheVersion)
463 setCachedVersion(version);
465 LOG_ERROR("Failed to retrieve version from database %s", databaseDebugName().ascii().data());
467 m_databaseAuthorizer->enable();
472 bool DatabaseBackendBase::setVersionInDatabase(const String& version, bool shouldCacheVersion)
474 // The INSERT will replace an existing entry for the database with the new version number, due to the UNIQUE ON CONFLICT REPLACE
475 // clause in the CREATE statement (see Database::performOpenAndVerify()).
476 String query(String("INSERT INTO ") + infoTableName + " (key, value) VALUES ('" + versionKey + "', ?);");
478 m_databaseAuthorizer->disable();
480 bool result = setTextValueInDatabase(m_sqliteDatabase, query, version);
482 if (shouldCacheVersion)
483 setCachedVersion(version);
485 LOG_ERROR("Failed to set version %s in database (%s)", version.ascii().data(), query.ascii().data());
487 m_databaseAuthorizer->enable();
492 void DatabaseBackendBase::setExpectedVersion(const String& version)
494 m_expectedVersion = version.isolatedCopy();
497 String DatabaseBackendBase::getCachedVersion() const
499 MutexLocker locker(guidMutex());
500 return guidToVersionMap().get(m_guid).isolatedCopy();
503 void DatabaseBackendBase::setCachedVersion(const String& actualVersion)
505 // Update the in memory database version map.
506 MutexLocker locker(guidMutex());
507 updateGuidVersionMap(m_guid, actualVersion);
510 bool DatabaseBackendBase::getActualVersionForTransaction(String &actualVersion)
512 ASSERT(m_sqliteDatabase.transactionInProgress());
513 // Note: In multi-process browsers the cached value may be inaccurate.
514 // So we retrieve the value from the database and update the cached value here.
515 return getVersionFromDatabase(actualVersion, true);
518 void DatabaseBackendBase::disableAuthorizer()
520 ASSERT(m_databaseAuthorizer);
521 m_databaseAuthorizer->disable();
524 void DatabaseBackendBase::enableAuthorizer()
526 ASSERT(m_databaseAuthorizer);
527 m_databaseAuthorizer->enable();
530 void DatabaseBackendBase::setAuthorizerReadOnly()
532 ASSERT(m_databaseAuthorizer);
533 m_databaseAuthorizer->setReadOnly();
536 void DatabaseBackendBase::setAuthorizerPermissions(int permissions)
538 ASSERT(m_databaseAuthorizer);
539 m_databaseAuthorizer->setPermissions(permissions);
542 bool DatabaseBackendBase::lastActionChangedDatabase()
544 ASSERT(m_databaseAuthorizer);
545 return m_databaseAuthorizer->lastActionChangedDatabase();
548 bool DatabaseBackendBase::lastActionWasInsert()
550 ASSERT(m_databaseAuthorizer);
551 return m_databaseAuthorizer->lastActionWasInsert();
554 void DatabaseBackendBase::resetDeletes()
556 ASSERT(m_databaseAuthorizer);
557 m_databaseAuthorizer->resetDeletes();
560 bool DatabaseBackendBase::hadDeletes()
562 ASSERT(m_databaseAuthorizer);
563 return m_databaseAuthorizer->hadDeletes();
566 void DatabaseBackendBase::resetAuthorizer()
568 if (m_databaseAuthorizer)
569 m_databaseAuthorizer->reset();
572 unsigned long long DatabaseBackendBase::maximumSize() const
574 return DatabaseTracker::tracker().getMaxSizeForDatabase(this);
577 void DatabaseBackendBase::incrementalVacuumIfNeeded()
580 SQLiteTransactionInProgressAutoCounter transactionCounter;
582 int64_t freeSpaceSize = m_sqliteDatabase.freeSpaceSize();
583 int64_t totalSize = m_sqliteDatabase.totalSize();
584 if (totalSize <= 10 * freeSpaceSize) {
585 int result = m_sqliteDatabase.runIncrementalVacuumCommand();
586 if (result != SQLResultOk)
587 m_frontend->logErrorMessage(formatErrorMessage("error vacuuming database", result, m_sqliteDatabase.lastErrorMsg()));
591 void DatabaseBackendBase::interrupt()
593 m_sqliteDatabase.interrupt();
596 bool DatabaseBackendBase::isInterrupted()
598 MutexLocker locker(m_sqliteDatabase.databaseMutex());
599 return m_sqliteDatabase.isInterrupted();
602 } // namespace WebCore
604 #endif // ENABLE(SQL_DATABASE)