This source file includes following definitions.
- formatErrorMessage
- retrieveTextResultFromDatabase
- setTextValueInDatabase
- guidMutex
- guidToVersionMap
- updateGuidVersionMap
- guidToDatabaseMap
- guidForOriginAndName
- databaseInfoTableName
- m_isSyncDatabase
- trace
- closeDatabase
- version
- m_openSucceeded
- setOpenSucceeded
- performOpenAndVerify
- securityOrigin
- stringIdentifier
- displayName
- estimatedSize
- fileName
- getVersionFromDatabase
- setVersionInDatabase
- setExpectedVersion
- getCachedVersion
- setCachedVersion
- getActualVersionForTransaction
- disableAuthorizer
- enableAuthorizer
- setAuthorizerPermissions
- lastActionChangedDatabase
- lastActionWasInsert
- resetDeletes
- hadDeletes
- resetAuthorizer
- maximumSize
- incrementalVacuumIfNeeded
- interrupt
- isInterrupted
- reportOpenDatabaseResult
- reportChangeVersionResult
- reportStartTransactionResult
- reportCommitTransactionResult
- reportExecuteStatementResult
- reportVacuumDatabaseResult
- logErrorMessage
- executionContext
#include "config.h"
#include "modules/webdatabase/DatabaseBackendBase.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/ExecutionContext.h"
#include "platform/Logging.h"
#include "modules/webdatabase/DatabaseAuthorizer.h"
#include "modules/webdatabase/DatabaseBase.h"
#include "modules/webdatabase/DatabaseContext.h"
#include "modules/webdatabase/DatabaseManager.h"
#include "modules/webdatabase/DatabaseTracker.h"
#include "modules/webdatabase/sqlite/SQLiteStatement.h"
#include "modules/webdatabase/sqlite/SQLiteTransaction.h"
#include "platform/weborigin/DatabaseIdentifier.h"
#include "public/platform/Platform.h"
#include "public/platform/WebDatabaseObserver.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
#include "wtf/PassRefPtr.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringHash.h"
namespace WebCore {
static const char versionKey[] = "WebKitDatabaseVersionKey";
static const char infoTableName[] = "__WebKitDatabaseInfoTable__";
static String formatErrorMessage(const char* message, int sqliteErrorCode, const char* sqliteErrorMessage)
{
return String::format("%s (%d %s)", message, sqliteErrorCode, sqliteErrorMessage);
}
static bool retrieveTextResultFromDatabase(SQLiteDatabase& db, const String& query, String& resultString)
{
SQLiteStatement statement(db, query);
int result = statement.prepare();
if (result != SQLResultOk) {
WTF_LOG_ERROR("Error (%i) preparing statement to read text result from database (%s)", result, query.ascii().data());
return false;
}
result = statement.step();
if (result == SQLResultRow) {
resultString = statement.getColumnText(0);
return true;
}
if (result == SQLResultDone) {
resultString = String();
return true;
}
WTF_LOG_ERROR("Error (%i) reading text result from database (%s)", result, query.ascii().data());
return false;
}
static bool setTextValueInDatabase(SQLiteDatabase& db, const String& query, const String& value)
{
SQLiteStatement statement(db, query);
int result = statement.prepare();
if (result != SQLResultOk) {
WTF_LOG_ERROR("Failed to prepare statement to set value in database (%s)", query.ascii().data());
return false;
}
statement.bindText(1, value);
result = statement.step();
if (result != SQLResultDone) {
WTF_LOG_ERROR("Failed to step statement to set value in database (%s)", query.ascii().data());
return false;
}
return true;
}
static Mutex& guidMutex()
{
AtomicallyInitializedStatic(Mutex&, mutex = *new Mutex);
return mutex;
}
typedef HashMap<DatabaseGuid, String> GuidVersionMap;
static GuidVersionMap& guidToVersionMap()
{
ASSERT(!guidMutex().tryLock());
DEFINE_STATIC_LOCAL(GuidVersionMap, map, ());
return map;
}
static inline void updateGuidVersionMap(DatabaseGuid guid, String newVersion)
{
ASSERT(!guidMutex().tryLock());
guidToVersionMap().set(guid, newVersion.isEmpty() ? String() : newVersion.isolatedCopy());
}
typedef HashMap<DatabaseGuid, HashSet<DatabaseBackendBase*>*> GuidDatabaseMap;
static GuidDatabaseMap& guidToDatabaseMap()
{
ASSERT(!guidMutex().tryLock());
DEFINE_STATIC_LOCAL(GuidDatabaseMap, map, ());
return map;
}
static DatabaseGuid guidForOriginAndName(const String& origin, const String& name)
{
ASSERT(!guidMutex().tryLock());
String stringID = origin + "/" + name;
typedef HashMap<String, int> IDGuidMap;
DEFINE_STATIC_LOCAL(IDGuidMap, stringIdentifierToGUIDMap, ());
DatabaseGuid guid = stringIdentifierToGUIDMap.get(stringID);
if (!guid) {
static int currentNewGUID = 1;
guid = currentNewGUID++;
stringIdentifierToGUIDMap.set(stringID, guid);
}
return guid;
}
const char* DatabaseBackendBase::databaseInfoTableName()
{
return infoTableName;
}
DatabaseBackendBase::DatabaseBackendBase(DatabaseContext* databaseContext, const String& name,
const String& expectedVersion, const String& displayName, unsigned long estimatedSize, DatabaseType databaseType)
: m_databaseContext(databaseContext)
, m_name(name.isolatedCopy())
, m_expectedVersion(expectedVersion.isolatedCopy())
, m_displayName(displayName.isolatedCopy())
, m_estimatedSize(estimatedSize)
, m_guid(0)
, m_opened(false)
, m_new(false)
, m_isSyncDatabase(databaseType == DatabaseType::Sync)
{
m_contextThreadSecurityOrigin = m_databaseContext->securityOrigin()->isolatedCopy();
m_databaseAuthorizer = DatabaseAuthorizer::create(infoTableName);
if (m_name.isNull())
m_name = "";
{
MutexLocker locker(guidMutex());
m_guid = guidForOriginAndName(securityOrigin()->toString(), name);
HashSet<DatabaseBackendBase*>* hashSet = guidToDatabaseMap().get(m_guid);
if (!hashSet) {
hashSet = new HashSet<DatabaseBackendBase*>;
guidToDatabaseMap().set(m_guid, hashSet);
}
hashSet->add(this);
}
m_filename = DatabaseManager::manager().fullPathForDatabase(securityOrigin(), m_name);
}
DatabaseBackendBase::~DatabaseBackendBase()
{
ASSERT(!m_opened);
}
void DatabaseBackendBase::trace(Visitor* visitor)
{
visitor->trace(m_databaseContext);
visitor->trace(m_sqliteDatabase);
visitor->trace(m_databaseAuthorizer);
}
void DatabaseBackendBase::closeDatabase()
{
if (!m_opened)
return;
m_sqliteDatabase.close();
m_opened = false;
databaseContext()->didCloseDatabase(*this);
DatabaseTracker::tracker().removeOpenDatabase(this);
{
MutexLocker locker(guidMutex());
HashSet<DatabaseBackendBase*>* hashSet = guidToDatabaseMap().get(m_guid);
ASSERT(hashSet);
ASSERT(hashSet->contains(this));
hashSet->remove(this);
if (hashSet->isEmpty()) {
guidToDatabaseMap().remove(m_guid);
delete hashSet;
guidToVersionMap().remove(m_guid);
}
}
}
String DatabaseBackendBase::version() const
{
return getCachedVersion();
}
class DoneCreatingDatabaseOnExitCaller {
public:
DoneCreatingDatabaseOnExitCaller(DatabaseBackendBase* database)
: m_database(database)
, m_openSucceeded(false)
{
}
~DoneCreatingDatabaseOnExitCaller()
{
if (!m_openSucceeded)
DatabaseTracker::tracker().failedToOpenDatabase(m_database);
}
void setOpenSucceeded() { m_openSucceeded = true; }
private:
DatabaseBackendBase* m_database;
bool m_openSucceeded;
};
bool DatabaseBackendBase::performOpenAndVerify(bool shouldSetVersionInNewDatabase, DatabaseError& error, String& errorMessage)
{
DoneCreatingDatabaseOnExitCaller onExitCaller(this);
ASSERT(errorMessage.isEmpty());
ASSERT(error == DatabaseError::None);
error = DatabaseError::InvalidDatabaseState;
const int maxSqliteBusyWaitTime = 30000;
if (!m_sqliteDatabase.open(m_filename, true)) {
reportOpenDatabaseResult(1, InvalidStateError, m_sqliteDatabase.lastError());
errorMessage = formatErrorMessage("unable to open database", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
return false;
}
if (!m_sqliteDatabase.turnOnIncrementalAutoVacuum())
WTF_LOG_ERROR("Unable to turn on incremental auto-vacuum (%d %s)", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
m_sqliteDatabase.setBusyTimeout(maxSqliteBusyWaitTime);
String currentVersion;
{
MutexLocker locker(guidMutex());
GuidVersionMap::iterator entry = guidToVersionMap().find(m_guid);
if (entry != guidToVersionMap().end()) {
currentVersion = entry->value.isNull() ? emptyString() : entry->value.isolatedCopy();
WTF_LOG(StorageAPI, "Current cached version for guid %i is %s", m_guid, currentVersion.ascii().data());
const int noSqliteBusyWaitTime = 0;
m_sqliteDatabase.setBusyTimeout(noSqliteBusyWaitTime);
String versionFromDatabase;
if (getVersionFromDatabase(versionFromDatabase, false)) {
currentVersion = versionFromDatabase;
updateGuidVersionMap(m_guid, currentVersion);
}
m_sqliteDatabase.setBusyTimeout(maxSqliteBusyWaitTime);
} else {
WTF_LOG(StorageAPI, "No cached version for guid %i", m_guid);
SQLiteTransaction transaction(m_sqliteDatabase);
transaction.begin();
if (!transaction.inProgress()) {
reportOpenDatabaseResult(2, InvalidStateError, m_sqliteDatabase.lastError());
errorMessage = formatErrorMessage("unable to open database, failed to start transaction", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
m_sqliteDatabase.close();
return false;
}
String tableName(infoTableName);
if (!m_sqliteDatabase.tableExists(tableName)) {
m_new = true;
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);")) {
reportOpenDatabaseResult(3, InvalidStateError, m_sqliteDatabase.lastError());
errorMessage = formatErrorMessage("unable to open database, failed to create 'info' table", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
transaction.rollback();
m_sqliteDatabase.close();
return false;
}
} else if (!getVersionFromDatabase(currentVersion, false)) {
reportOpenDatabaseResult(4, InvalidStateError, m_sqliteDatabase.lastError());
errorMessage = formatErrorMessage("unable to open database, failed to read current version", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
transaction.rollback();
m_sqliteDatabase.close();
return false;
}
if (currentVersion.length()) {
WTF_LOG(StorageAPI, "Retrieved current version %s from database %s", currentVersion.ascii().data(), databaseDebugName().ascii().data());
} else if (!m_new || shouldSetVersionInNewDatabase) {
WTF_LOG(StorageAPI, "Setting version %s in database %s that was just created", m_expectedVersion.ascii().data(), databaseDebugName().ascii().data());
if (!setVersionInDatabase(m_expectedVersion, false)) {
reportOpenDatabaseResult(5, InvalidStateError, m_sqliteDatabase.lastError());
errorMessage = formatErrorMessage("unable to open database, failed to write current version", m_sqliteDatabase.lastError(), m_sqliteDatabase.lastErrorMsg());
transaction.rollback();
m_sqliteDatabase.close();
return false;
}
currentVersion = m_expectedVersion;
}
updateGuidVersionMap(m_guid, currentVersion);
transaction.commit();
}
}
if (currentVersion.isNull()) {
WTF_LOG(StorageAPI, "Database %s does not have its version set", databaseDebugName().ascii().data());
currentVersion = "";
}
if ((!m_new || shouldSetVersionInNewDatabase) && m_expectedVersion.length() && m_expectedVersion != currentVersion) {
reportOpenDatabaseResult(6, InvalidStateError, 0);
errorMessage = "unable to open database, version mismatch, '" + m_expectedVersion + "' does not match the currentVersion of '" + currentVersion + "'";
m_sqliteDatabase.close();
return false;
}
ASSERT(m_databaseAuthorizer);
m_sqliteDatabase.setAuthorizer(m_databaseAuthorizer.get());
databaseContext()->didOpenDatabase(*this);
DatabaseTracker::tracker().addOpenDatabase(this);
m_opened = true;
error = DatabaseError::None;
onExitCaller.setOpenSucceeded();
if (m_new && !shouldSetVersionInNewDatabase)
m_expectedVersion = "";
reportOpenDatabaseResult(0, -1, 0);
return true;
}
SecurityOrigin* DatabaseBackendBase::securityOrigin() const
{
return m_contextThreadSecurityOrigin.get();
}
String DatabaseBackendBase::stringIdentifier() const
{
return m_name.isolatedCopy();
}
String DatabaseBackendBase::displayName() const
{
return m_displayName.isolatedCopy();
}
unsigned long DatabaseBackendBase::estimatedSize() const
{
return m_estimatedSize;
}
String DatabaseBackendBase::fileName() const
{
return m_filename.isolatedCopy();
}
bool DatabaseBackendBase::getVersionFromDatabase(String& version, bool shouldCacheVersion)
{
String query(String("SELECT value FROM ") + infoTableName + " WHERE key = '" + versionKey + "';");
m_databaseAuthorizer->disable();
bool result = retrieveTextResultFromDatabase(m_sqliteDatabase, query, version);
if (result) {
if (shouldCacheVersion)
setCachedVersion(version);
} else
WTF_LOG_ERROR("Failed to retrieve version from database %s", databaseDebugName().ascii().data());
m_databaseAuthorizer->enable();
return result;
}
bool DatabaseBackendBase::setVersionInDatabase(const String& version, bool shouldCacheVersion)
{
String query(String("INSERT INTO ") + infoTableName + " (key, value) VALUES ('" + versionKey + "', ?);");
m_databaseAuthorizer->disable();
bool result = setTextValueInDatabase(m_sqliteDatabase, query, version);
if (result) {
if (shouldCacheVersion)
setCachedVersion(version);
} else
WTF_LOG_ERROR("Failed to set version %s in database (%s)", version.ascii().data(), query.ascii().data());
m_databaseAuthorizer->enable();
return result;
}
void DatabaseBackendBase::setExpectedVersion(const String& version)
{
m_expectedVersion = version.isolatedCopy();
}
String DatabaseBackendBase::getCachedVersion() const
{
MutexLocker locker(guidMutex());
return guidToVersionMap().get(m_guid).isolatedCopy();
}
void DatabaseBackendBase::setCachedVersion(const String& actualVersion)
{
MutexLocker locker(guidMutex());
updateGuidVersionMap(m_guid, actualVersion);
}
bool DatabaseBackendBase::getActualVersionForTransaction(String &actualVersion)
{
ASSERT(m_sqliteDatabase.transactionInProgress());
return getVersionFromDatabase(actualVersion, true);
}
void DatabaseBackendBase::disableAuthorizer()
{
ASSERT(m_databaseAuthorizer);
m_databaseAuthorizer->disable();
}
void DatabaseBackendBase::enableAuthorizer()
{
ASSERT(m_databaseAuthorizer);
m_databaseAuthorizer->enable();
}
void DatabaseBackendBase::setAuthorizerPermissions(int permissions)
{
ASSERT(m_databaseAuthorizer);
m_databaseAuthorizer->setPermissions(permissions);
}
bool DatabaseBackendBase::lastActionChangedDatabase()
{
ASSERT(m_databaseAuthorizer);
return m_databaseAuthorizer->lastActionChangedDatabase();
}
bool DatabaseBackendBase::lastActionWasInsert()
{
ASSERT(m_databaseAuthorizer);
return m_databaseAuthorizer->lastActionWasInsert();
}
void DatabaseBackendBase::resetDeletes()
{
ASSERT(m_databaseAuthorizer);
m_databaseAuthorizer->resetDeletes();
}
bool DatabaseBackendBase::hadDeletes()
{
ASSERT(m_databaseAuthorizer);
return m_databaseAuthorizer->hadDeletes();
}
void DatabaseBackendBase::resetAuthorizer()
{
if (m_databaseAuthorizer)
m_databaseAuthorizer->reset();
}
unsigned long long DatabaseBackendBase::maximumSize() const
{
return DatabaseTracker::tracker().getMaxSizeForDatabase(this);
}
void DatabaseBackendBase::incrementalVacuumIfNeeded()
{
int64_t freeSpaceSize = m_sqliteDatabase.freeSpaceSize();
int64_t totalSize = m_sqliteDatabase.totalSize();
if (totalSize <= 10 * freeSpaceSize) {
int result = m_sqliteDatabase.runIncrementalVacuumCommand();
reportVacuumDatabaseResult(result);
if (result != SQLResultOk)
logErrorMessage(formatErrorMessage("error vacuuming database", result, m_sqliteDatabase.lastErrorMsg()));
}
}
void DatabaseBackendBase::interrupt()
{
m_sqliteDatabase.interrupt();
}
bool DatabaseBackendBase::isInterrupted()
{
MutexLocker locker(m_sqliteDatabase.databaseMutex());
return m_sqliteDatabase.isInterrupted();
}
void DatabaseBackendBase::reportOpenDatabaseResult(int errorSite, int webSqlErrorCode, int sqliteErrorCode)
{
if (blink::Platform::current()->databaseObserver()) {
blink::Platform::current()->databaseObserver()->reportOpenDatabaseResult(
createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
stringIdentifier(), isSyncDatabase(),
errorSite, webSqlErrorCode, sqliteErrorCode);
}
}
void DatabaseBackendBase::reportChangeVersionResult(int errorSite, int webSqlErrorCode, int sqliteErrorCode)
{
if (blink::Platform::current()->databaseObserver()) {
blink::Platform::current()->databaseObserver()->reportChangeVersionResult(
createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
stringIdentifier(), isSyncDatabase(),
errorSite, webSqlErrorCode, sqliteErrorCode);
}
}
void DatabaseBackendBase::reportStartTransactionResult(int errorSite, int webSqlErrorCode, int sqliteErrorCode)
{
if (blink::Platform::current()->databaseObserver()) {
blink::Platform::current()->databaseObserver()->reportStartTransactionResult(
createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
stringIdentifier(), isSyncDatabase(),
errorSite, webSqlErrorCode, sqliteErrorCode);
}
}
void DatabaseBackendBase::reportCommitTransactionResult(int errorSite, int webSqlErrorCode, int sqliteErrorCode)
{
if (blink::Platform::current()->databaseObserver()) {
blink::Platform::current()->databaseObserver()->reportCommitTransactionResult(
createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
stringIdentifier(), isSyncDatabase(),
errorSite, webSqlErrorCode, sqliteErrorCode);
}
}
void DatabaseBackendBase::reportExecuteStatementResult(int errorSite, int webSqlErrorCode, int sqliteErrorCode)
{
if (blink::Platform::current()->databaseObserver()) {
blink::Platform::current()->databaseObserver()->reportExecuteStatementResult(
createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
stringIdentifier(), isSyncDatabase(),
errorSite, webSqlErrorCode, sqliteErrorCode);
}
}
void DatabaseBackendBase::reportVacuumDatabaseResult(int sqliteErrorCode)
{
if (blink::Platform::current()->databaseObserver()) {
blink::Platform::current()->databaseObserver()->reportVacuumDatabaseResult(
createDatabaseIdentifierFromSecurityOrigin(securityOrigin()),
stringIdentifier(), isSyncDatabase(), sqliteErrorCode);
}
}
void DatabaseBackendBase::logErrorMessage(const String& message)
{
executionContext()->addConsoleMessage(StorageMessageSource, ErrorMessageLevel, message);
}
ExecutionContext* DatabaseBackendBase::executionContext() const
{
return databaseContext()->executionContext();
}
}