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 "SQLiteDatabaseTracker.h"
44 #include "SQLiteStatement.h"
45 #include "SQLiteTransaction.h"
46 #include "SecurityOrigin.h"
47 #include <wtf/HashMap.h>
48 #include <wtf/HashSet.h>
49 #include <wtf/NeverDestroyed.h>
50 #include <wtf/PassRefPtr.h>
51 #include <wtf/RefPtr.h>
52 #include <wtf/StdLibExtras.h>
53 #include <wtf/text/CString.h>
54 #include <wtf/text/StringHash.h>
56 // Registering "opened" databases with the DatabaseTracker
57 // =======================================================
58 // The DatabaseTracker maintains a list of databases that have been
59 // "opened" so that the client can call interrupt or delete on every database
60 // associated with a DatabaseBackendContext.
62 // We will only call DatabaseTracker::addOpenDatabase() to add the database
63 // to the tracker as opened when we've succeeded in opening the database,
64 // and will set m_opened to true. Similarly, we only call
65 // DatabaseTracker::removeOpenDatabase() to remove the database from the
66 // tracker when we set m_opened to false in closeDatabase(). This sets up
67 // a simple symmetry between open and close operations, and a direct
68 // correlation to adding and removing databases from the tracker's list,
69 // thus ensuring that we have a correct list for the interrupt and
70 // delete operations to work on.
72 // The only databases instances not tracked by the tracker's open database
73 // list are the ones that have not been added yet, or the ones that we
74 // attempted an open on but failed to. Such instances only exist in the
75 // DatabaseServer's factory methods for creating database backends.
77 // The factory methods will either call openAndVerifyVersion() or
78 // performOpenAndVerify(). These methods will add the newly instantiated
79 // database backend if they succeed in opening the requested database.
80 // In the case of failure to open the database, the factory methods will
81 // simply discard the newly instantiated database backend when they return.
82 // The ref counting mechanims will automatically destruct the un-added
83 // (and un-returned) databases instances.
87 static const char versionKey[] = "WebKitDatabaseVersionKey";
88 static const char infoTableName[] = "__WebKitDatabaseInfoTable__";
90 static String formatErrorMessage(const char* message, int sqliteErrorCode, const char* sqliteErrorMessage)
92 return String::format("%s (%d %s)", message, sqliteErrorCode, sqliteErrorMessage);
95 static bool retrieveTextResultFromDatabase(SQLiteDatabase& db, const String& query, String& resultString)
97 SQLiteStatement statement(db, query);
98 int result = statement.prepare();
100 if (result != SQLResultOk) {
101 LOG_ERROR("Error (%i) preparing statement to read text result from database (%s)", result, query.ascii().data());
105 result = statement.step();
106 if (result == SQLResultRow) {
107 resultString = statement.getColumnText(0);
110 if (result == SQLResultDone) {
111 resultString = String();
115 LOG_ERROR("Error (%i) reading text result from database (%s)", result, query.ascii().data());
119 static bool setTextValueInDatabase(SQLiteDatabase& db, const String& query, const String& value)
121 SQLiteStatement statement(db, query);
122 int result = statement.prepare();
124 if (result != SQLResultOk) {
125 LOG_ERROR("Failed to prepare statement to set value in database (%s)", query.ascii().data());
129 statement.bindText(1, value);
131 result = statement.step();
132 if (result != SQLResultDone) {
133 LOG_ERROR("Failed to step statement to set value in database (%s)", query.ascii().data());
140 // FIXME: move all guid-related functions to a DatabaseVersionTracker class.
141 static std::mutex& guidMutex()
143 static std::once_flag onceFlag;
144 static std::mutex* mutex;
146 std::call_once(onceFlag, []{
147 mutex = std::make_unique<std::mutex>().release();
153 typedef HashMap<DatabaseGuid, String> GuidVersionMap;
154 static GuidVersionMap& guidToVersionMap()
156 // Ensure the the mutex is locked.
157 ASSERT(!guidMutex().try_lock());
159 static NeverDestroyed<GuidVersionMap> map;
163 // NOTE: Caller must lock guidMutex().
164 static inline void updateGuidVersionMap(DatabaseGuid guid, String newVersion)
166 // Ensure the the mutex is locked.
167 ASSERT(!guidMutex().try_lock());
169 // Note: It is not safe to put an empty string into the guidToVersionMap() map.
170 // That's because the map is cross-thread, but empty strings are per-thread.
171 // The copy() function makes a version of the string you can use on the current
172 // thread, but we need a string we can keep in a cross-thread data structure.
173 // FIXME: This is a quite-awkward restriction to have to program with.
175 // Map null string to empty string (see comment above).
176 guidToVersionMap().set(guid, newVersion.isEmpty() ? String() : newVersion.isolatedCopy());
179 typedef HashMap<DatabaseGuid, std::unique_ptr<HashSet<DatabaseBackendBase*>>> GuidDatabaseMap;
181 static GuidDatabaseMap& guidToDatabaseMap()
183 // Ensure the the mutex is locked.
184 ASSERT(!guidMutex().try_lock());
186 static NeverDestroyed<GuidDatabaseMap> map;
190 static DatabaseGuid guidForOriginAndName(const String& origin, const String& name)
192 // Ensure the the mutex is locked.
193 ASSERT(!guidMutex().try_lock());
195 String stringID = origin + "/" + name;
197 typedef HashMap<String, int> IDGuidMap;
198 static NeverDestroyed<HashMap<String, int>> map;
199 DatabaseGuid guid = map.get().get(stringID);
201 static int currentNewGUID = 1;
202 guid = currentNewGUID++;
203 map.get().set(stringID, guid);
210 const char* DatabaseBackendBase::databaseInfoTableName()
212 return infoTableName;
215 #if !LOG_DISABLED || !ERROR_DISABLED
216 String DatabaseBackendBase::databaseDebugName() const
218 return m_contextThreadSecurityOrigin->toString() + "::" + m_name;
222 DatabaseBackendBase::DatabaseBackendBase(PassRefPtr<DatabaseBackendContext> databaseContext, const String& name,
223 const String& expectedVersion, const String& displayName, unsigned long estimatedSize, DatabaseType databaseType)
224 : m_databaseContext(databaseContext)
225 , m_name(name.isolatedCopy())
226 , m_expectedVersion(expectedVersion.isolatedCopy())
227 , m_displayName(displayName.isolatedCopy())
228 , m_estimatedSize(estimatedSize)
231 , m_isSyncDatabase(databaseType == DatabaseType::Sync)
233 m_contextThreadSecurityOrigin = m_databaseContext->securityOrigin()->isolatedCopy();
235 m_databaseAuthorizer = DatabaseAuthorizer::create(infoTableName);
238 m_name = emptyString();
241 std::lock_guard<std::mutex> locker(guidMutex());
243 m_guid = guidForOriginAndName(securityOrigin()->toString(), name);
244 std::unique_ptr<HashSet<DatabaseBackendBase*>>& hashSet = guidToDatabaseMap().add(m_guid, nullptr).iterator->value;
246 hashSet = std::make_unique<HashSet<DatabaseBackendBase*>>();
250 m_filename = DatabaseManager::manager().fullPathForDatabase(securityOrigin(), m_name);
253 DatabaseBackendBase::~DatabaseBackendBase()
255 // SQLite is "multi-thread safe", but each database handle can only be used
256 // on a single thread at a time.
258 // For DatabaseBackend, we open the SQLite database on the DatabaseThread,
259 // and hence we should also close it on that same thread. This means that the
260 // SQLite database need to be closed by another mechanism (see
261 // DatabaseContext::stopDatabases()). By the time we get here, the SQLite
262 // database should have already been closed.
267 void DatabaseBackendBase::closeDatabase()
272 m_sqliteDatabase.close();
274 // See comment at the top this file regarding calling removeOpenDatabase().
275 DatabaseTracker::tracker().removeOpenDatabase(this);
277 std::lock_guard<std::mutex> locker(guidMutex());
279 auto it = guidToDatabaseMap().find(m_guid);
280 ASSERT(it != guidToDatabaseMap().end());
282 ASSERT(it->value->contains(this));
283 it->value->remove(this);
284 if (it->value->isEmpty()) {
285 guidToDatabaseMap().remove(it);
286 guidToVersionMap().remove(m_guid);
291 String DatabaseBackendBase::version() const
293 // Note: In multi-process browsers the cached value may be accurate, but we cannot read the
294 // actual version from the database without potentially inducing a deadlock.
295 // FIXME: Add an async version getter to the DatabaseAPI.
296 return getCachedVersion();
299 class DoneCreatingDatabaseOnExitCaller {
301 DoneCreatingDatabaseOnExitCaller(DatabaseBackendBase* database)
302 : m_database(database)
303 , m_openSucceeded(false)
306 ~DoneCreatingDatabaseOnExitCaller()
308 DatabaseTracker::tracker().doneCreatingDatabase(m_database);
311 void setOpenSucceeded() { m_openSucceeded = true; }
314 DatabaseBackendBase* m_database;
315 bool m_openSucceeded;
318 bool DatabaseBackendBase::performOpenAndVerify(bool shouldSetVersionInNewDatabase, DatabaseError& error, String& errorMessage)
320 DoneCreatingDatabaseOnExitCaller onExitCaller(this);
321 ASSERT(errorMessage.isEmpty());
322 ASSERT(error == DatabaseError::None); // Better not have any errors already.
323 error = DatabaseError::InvalidDatabaseState; // Presumed failure. We'll clear it if we succeed below.
325 const int maxSqliteBusyWaitTime = 30000;
329 // Make sure we wait till the background removal of the empty database files finished before trying to open any database.
330 MutexLocker locker(DatabaseTracker::openDatabaseMutex());
334 SQLiteTransactionInProgressAutoCounter transactionCounter;
336 if (!m_sqliteDatabase.open(m_filename, true)) {
337 errorMessage = formatErrorMessage("unable to open database", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
340 if (!m_sqliteDatabase.turnOnIncrementalAutoVacuum())
341 LOG_ERROR("Unable to turn on incremental auto-vacuum (%d %s)", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
343 m_sqliteDatabase.setBusyTimeout(maxSqliteBusyWaitTime);
345 String currentVersion;
347 std::lock_guard<std::mutex> locker(guidMutex());
349 auto entry = guidToVersionMap().find(m_guid);
350 if (entry != guidToVersionMap().end()) {
351 // Map null string to empty string (see updateGuidVersionMap()).
352 currentVersion = entry->value.isNull() ? emptyString() : entry->value.isolatedCopy();
353 LOG(StorageAPI, "Current cached version for guid %i is %s", m_guid, currentVersion.ascii().data());
355 LOG(StorageAPI, "No cached version for guid %i", m_guid);
357 SQLiteTransaction transaction(m_sqliteDatabase);
359 if (!transaction.inProgress()) {
360 errorMessage = formatErrorMessage("unable to open database, failed to start transaction", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
361 m_sqliteDatabase.close();
365 String tableName(infoTableName);
366 if (!m_sqliteDatabase.tableExists(tableName)) {
369 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);")) {
370 errorMessage = formatErrorMessage("unable to open database, failed to create 'info' table", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
371 transaction.rollback();
372 m_sqliteDatabase.close();
375 } else if (!getVersionFromDatabase(currentVersion, false)) {
376 errorMessage = formatErrorMessage("unable to open database, failed to read current version", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
377 transaction.rollback();
378 m_sqliteDatabase.close();
382 if (currentVersion.length()) {
383 LOG(StorageAPI, "Retrieved current version %s from database %s", currentVersion.ascii().data(), databaseDebugName().ascii().data());
384 } else if (!m_new || shouldSetVersionInNewDatabase) {
385 LOG(StorageAPI, "Setting version %s in database %s that was just created", m_expectedVersion.ascii().data(), databaseDebugName().ascii().data());
386 if (!setVersionInDatabase(m_expectedVersion, false)) {
387 errorMessage = formatErrorMessage("unable to open database, failed to write current version", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
388 transaction.rollback();
389 m_sqliteDatabase.close();
392 currentVersion = m_expectedVersion;
394 updateGuidVersionMap(m_guid, currentVersion);
395 transaction.commit();
399 if (currentVersion.isNull()) {
400 LOG(StorageAPI, "Database %s does not have its version set", databaseDebugName().ascii().data());
404 // If the expected version isn't the empty string, ensure that the current database version we have matches that version. Otherwise, set an exception.
405 // If the expected version is the empty string, then we always return with whatever version of the database we have.
406 if ((!m_new || shouldSetVersionInNewDatabase) && m_expectedVersion.length() && m_expectedVersion != currentVersion) {
407 errorMessage = "unable to open database, version mismatch, '" + m_expectedVersion + "' does not match the currentVersion of '" + currentVersion + "'";
408 m_sqliteDatabase.close();
412 ASSERT(m_databaseAuthorizer);
413 m_sqliteDatabase.setAuthorizer(m_databaseAuthorizer);
415 // See comment at the top this file regarding calling addOpenDatabase().
416 DatabaseTracker::tracker().addOpenDatabase(this);
420 error = DatabaseError::None; // Clear the presumed error from above.
421 onExitCaller.setOpenSucceeded();
423 if (m_new && !shouldSetVersionInNewDatabase)
424 m_expectedVersion = ""; // The caller provided a creationCallback which will set the expected version.
428 SecurityOrigin* DatabaseBackendBase::securityOrigin() const
430 return m_contextThreadSecurityOrigin.get();
433 String DatabaseBackendBase::stringIdentifier() const
435 // Return a deep copy for ref counting thread safety
436 return m_name.isolatedCopy();
439 String DatabaseBackendBase::displayName() const
441 // Return a deep copy for ref counting thread safety
442 return m_displayName.isolatedCopy();
445 unsigned long DatabaseBackendBase::estimatedSize() const
447 return m_estimatedSize;
450 String DatabaseBackendBase::fileName() const
452 // Return a deep copy for ref counting thread safety
453 return m_filename.isolatedCopy();
456 DatabaseDetails DatabaseBackendBase::details() const
458 return DatabaseDetails(stringIdentifier(), displayName(), estimatedSize(), 0);
461 bool DatabaseBackendBase::getVersionFromDatabase(String& version, bool shouldCacheVersion)
463 String query(String("SELECT value FROM ") + infoTableName + " WHERE key = '" + versionKey + "';");
465 m_databaseAuthorizer->disable();
467 bool result = retrieveTextResultFromDatabase(m_sqliteDatabase, query, version);
469 if (shouldCacheVersion)
470 setCachedVersion(version);
472 LOG_ERROR("Failed to retrieve version from database %s", databaseDebugName().ascii().data());
474 m_databaseAuthorizer->enable();
479 bool DatabaseBackendBase::setVersionInDatabase(const String& version, bool shouldCacheVersion)
481 // The INSERT will replace an existing entry for the database with the new version number, due to the UNIQUE ON CONFLICT REPLACE
482 // clause in the CREATE statement (see Database::performOpenAndVerify()).
483 String query(String("INSERT INTO ") + infoTableName + " (key, value) VALUES ('" + versionKey + "', ?);");
485 m_databaseAuthorizer->disable();
487 bool result = setTextValueInDatabase(m_sqliteDatabase, query, version);
489 if (shouldCacheVersion)
490 setCachedVersion(version);
492 LOG_ERROR("Failed to set version %s in database (%s)", version.ascii().data(), query.ascii().data());
494 m_databaseAuthorizer->enable();
499 void DatabaseBackendBase::setExpectedVersion(const String& version)
501 m_expectedVersion = version.isolatedCopy();
504 String DatabaseBackendBase::getCachedVersion() const
506 std::lock_guard<std::mutex> locker(guidMutex());
508 return guidToVersionMap().get(m_guid).isolatedCopy();
511 void DatabaseBackendBase::setCachedVersion(const String& actualVersion)
513 // Update the in memory database version map.
514 std::lock_guard<std::mutex> locker(guidMutex());
516 updateGuidVersionMap(m_guid, actualVersion);
519 bool DatabaseBackendBase::getActualVersionForTransaction(String &actualVersion)
521 ASSERT(m_sqliteDatabase.transactionInProgress());
522 // Note: In multi-process browsers the cached value may be inaccurate.
523 // So we retrieve the value from the database and update the cached value here.
524 return getVersionFromDatabase(actualVersion, true);
527 void DatabaseBackendBase::disableAuthorizer()
529 ASSERT(m_databaseAuthorizer);
530 m_databaseAuthorizer->disable();
533 void DatabaseBackendBase::enableAuthorizer()
535 ASSERT(m_databaseAuthorizer);
536 m_databaseAuthorizer->enable();
539 void DatabaseBackendBase::setAuthorizerReadOnly()
541 ASSERT(m_databaseAuthorizer);
542 m_databaseAuthorizer->setReadOnly();
545 void DatabaseBackendBase::setAuthorizerPermissions(int permissions)
547 ASSERT(m_databaseAuthorizer);
548 m_databaseAuthorizer->setPermissions(permissions);
551 bool DatabaseBackendBase::lastActionChangedDatabase()
553 ASSERT(m_databaseAuthorizer);
554 return m_databaseAuthorizer->lastActionChangedDatabase();
557 bool DatabaseBackendBase::lastActionWasInsert()
559 ASSERT(m_databaseAuthorizer);
560 return m_databaseAuthorizer->lastActionWasInsert();
563 void DatabaseBackendBase::resetDeletes()
565 ASSERT(m_databaseAuthorizer);
566 m_databaseAuthorizer->resetDeletes();
569 bool DatabaseBackendBase::hadDeletes()
571 ASSERT(m_databaseAuthorizer);
572 return m_databaseAuthorizer->hadDeletes();
575 void DatabaseBackendBase::resetAuthorizer()
577 if (m_databaseAuthorizer)
578 m_databaseAuthorizer->reset();
581 unsigned long long DatabaseBackendBase::maximumSize() const
583 return DatabaseTracker::tracker().getMaxSizeForDatabase(this);
586 void DatabaseBackendBase::incrementalVacuumIfNeeded()
588 SQLiteTransactionInProgressAutoCounter transactionCounter;
590 int64_t freeSpaceSize = m_sqliteDatabase.freeSpaceSize();
591 int64_t totalSize = m_sqliteDatabase.totalSize();
592 if (totalSize <= 10 * freeSpaceSize) {
593 int result = m_sqliteDatabase.runIncrementalVacuumCommand();
594 if (result != SQLResultOk)
595 m_frontend->logErrorMessage(formatErrorMessage("error vacuuming database", result, m_sqliteDatabase.lastErrorMsg()));
599 void DatabaseBackendBase::interrupt()
601 m_sqliteDatabase.interrupt();
604 bool DatabaseBackendBase::isInterrupted()
606 MutexLocker locker(m_sqliteDatabase.databaseMutex());
607 return m_sqliteDatabase.isInterrupted();
610 } // namespace WebCore
612 #endif // ENABLE(SQL_DATABASE)