2 * Copyright (C) 2015, 2016 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
27 #include "UniqueIDBDatabase.h"
29 #if ENABLE(INDEXED_DATABASE)
31 #include "IDBCursorInfo.h"
32 #include "IDBGetAllRecordsData.h"
33 #include "IDBGetAllResult.h"
34 #include "IDBGetRecordData.h"
35 #include "IDBIterateCursorData.h"
36 #include "IDBKeyRangeData.h"
37 #include "IDBResultData.h"
38 #include "IDBServer.h"
39 #include "IDBTransactionInfo.h"
42 #include "ScopeGuard.h"
43 #include "SerializedScriptValue.h"
44 #include "UniqueIDBDatabaseConnection.h"
45 #include <heap/HeapInlines.h>
46 #include <runtime/AuxiliaryBarrierInlines.h>
47 #include <runtime/StructureInlines.h>
48 #include <wtf/MainThread.h>
49 #include <wtf/NeverDestroyed.h>
50 #include <wtf/ThreadSafeRefCounted.h>
57 UniqueIDBDatabase::UniqueIDBDatabase(IDBServer& server, const IDBDatabaseIdentifier& identifier)
59 , m_identifier(identifier)
60 , m_operationAndTransactionTimer(*this, &UniqueIDBDatabase::operationAndTransactionTimerFired)
62 LOG(IndexedDB, "UniqueIDBDatabase::UniqueIDBDatabase() (%p) %s", this, m_identifier.debugString().utf8().data());
65 UniqueIDBDatabase::~UniqueIDBDatabase()
67 LOG(IndexedDB, "UniqueIDBDatabase::~UniqueIDBDatabase() (%p) %s", this, m_identifier.debugString().utf8().data());
68 ASSERT(isMainThread());
69 ASSERT(!hasAnyPendingCallbacks());
70 ASSERT(!hasUnfinishedTransactions());
71 ASSERT(m_pendingTransactions.isEmpty());
72 ASSERT(m_openDatabaseConnections.isEmpty());
73 ASSERT(m_clientClosePendingDatabaseConnections.isEmpty());
74 ASSERT(m_serverClosePendingDatabaseConnections.isEmpty());
75 ASSERT(!m_queuedTaskCount);
78 const IDBDatabaseInfo& UniqueIDBDatabase::info() const
80 RELEASE_ASSERT(m_databaseInfo);
81 return *m_databaseInfo;
84 void UniqueIDBDatabase::openDatabaseConnection(IDBConnectionToClient& connection, const IDBRequestData& requestData)
86 LOG(IndexedDB, "UniqueIDBDatabase::openDatabaseConnection");
87 ASSERT(!m_hardClosedForUserDelete);
89 m_pendingOpenDBRequests.add(ServerOpenDBRequest::create(connection, requestData));
91 // An open operation is already in progress, so we can't possibly handle this one yet.
92 if (m_isOpeningBackingStore)
95 handleDatabaseOperations();
98 bool UniqueIDBDatabase::hasAnyPendingCallbacks() const
100 return !m_errorCallbacks.isEmpty()
101 || !m_keyDataCallbacks.isEmpty()
102 || !m_getResultCallbacks.isEmpty()
103 || !m_getAllResultsCallbacks.isEmpty()
104 || !m_countCallbacks.isEmpty();
107 bool UniqueIDBDatabase::isVersionChangeInProgress()
110 if (m_versionChangeTransaction)
111 ASSERT(m_versionChangeDatabaseConnection);
114 return m_versionChangeDatabaseConnection;
117 void UniqueIDBDatabase::performCurrentOpenOperation()
119 LOG(IndexedDB, "(main) UniqueIDBDatabase::performCurrentOpenOperation (%p)", this);
121 ASSERT(m_currentOpenDBRequest);
122 ASSERT(m_currentOpenDBRequest->isOpenRequest());
124 if (!m_databaseInfo) {
125 if (!m_isOpeningBackingStore) {
126 m_isOpeningBackingStore = true;
127 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::openBackingStore, m_identifier));
133 // If we previously started a version change operation but were blocked by having open connections,
134 // we might now be unblocked.
135 if (m_versionChangeDatabaseConnection) {
136 if (!m_versionChangeTransaction && !hasAnyOpenConnections())
137 startVersionChangeTransaction();
141 // 3.3.1 Opening a database
142 // If requested version is undefined, then let requested version be 1 if db was created in the previous step,
143 // or the current version of db otherwise.
144 uint64_t requestedVersion = m_currentOpenDBRequest->requestData().requestedVersion();
145 if (!requestedVersion)
146 requestedVersion = m_databaseInfo->version() ? m_databaseInfo->version() : 1;
148 // 3.3.1 Opening a database
149 // If the database version higher than the requested version, abort these steps and return a VersionError.
150 if (requestedVersion < m_databaseInfo->version()) {
151 auto result = IDBResultData::error(m_currentOpenDBRequest->requestData().requestIdentifier(), IDBError(IDBDatabaseException::VersionError));
152 m_currentOpenDBRequest->connection().didOpenDatabase(result);
153 m_currentOpenDBRequest = nullptr;
158 if (!m_backingStoreOpenError.isNull()) {
159 auto result = IDBResultData::error(m_currentOpenDBRequest->requestData().requestIdentifier(), m_backingStoreOpenError);
160 m_currentOpenDBRequest->connection().didOpenDatabase(result);
161 m_currentOpenDBRequest = nullptr;
166 Ref<UniqueIDBDatabaseConnection> connection = UniqueIDBDatabaseConnection::create(*this, *m_currentOpenDBRequest);
168 if (requestedVersion == m_databaseInfo->version()) {
169 auto* rawConnection = &connection.get();
170 addOpenDatabaseConnection(WTFMove(connection));
172 auto result = IDBResultData::openDatabaseSuccess(m_currentOpenDBRequest->requestData().requestIdentifier(), *rawConnection);
173 m_currentOpenDBRequest->connection().didOpenDatabase(result);
174 m_currentOpenDBRequest = nullptr;
179 ASSERT(!m_versionChangeDatabaseConnection);
180 m_versionChangeDatabaseConnection = WTFMove(connection);
182 // 3.3.7 "versionchange" transaction steps
183 // If there's no other open connections to this database, the version change process can begin immediately.
184 if (!hasAnyOpenConnections()) {
185 startVersionChangeTransaction();
189 // Otherwise we have to notify all those open connections and wait for them to close.
190 maybeNotifyConnectionsOfVersionChange();
193 void UniqueIDBDatabase::performCurrentDeleteOperation()
195 ASSERT(isMainThread());
196 LOG(IndexedDB, "(main) UniqueIDBDatabase::performCurrentDeleteOperation - %s", m_identifier.debugString().utf8().data());
198 ASSERT(m_currentOpenDBRequest);
199 ASSERT(m_currentOpenDBRequest->isDeleteRequest());
201 if (m_deleteBackingStoreInProgress)
204 if (hasAnyOpenConnections()) {
205 maybeNotifyConnectionsOfVersionChange();
209 if (hasUnfinishedTransactions())
212 ASSERT(!hasAnyPendingCallbacks());
213 ASSERT(m_pendingTransactions.isEmpty());
214 ASSERT(m_openDatabaseConnections.isEmpty());
216 // It's possible to have multiple delete requests queued up in a row.
217 // In that scenario only the first request will actually have to delete the database.
218 // Subsequent requests can immediately notify their completion.
220 if (!m_deleteBackingStoreInProgress) {
221 if (!m_databaseInfo && m_mostRecentDeletedDatabaseInfo)
222 didDeleteBackingStore(0);
224 m_deleteBackingStoreInProgress = true;
225 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::deleteBackingStore, m_identifier));
230 void UniqueIDBDatabase::deleteBackingStore(const IDBDatabaseIdentifier& identifier)
232 ASSERT(!isMainThread());
233 LOG(IndexedDB, "(db) UniqueIDBDatabase::deleteBackingStore");
235 uint64_t deletedVersion = 0;
237 if (m_backingStore) {
238 m_backingStore->deleteBackingStore();
239 m_backingStore = nullptr;
240 m_backingStoreSupportsSimultaneousTransactions = false;
241 m_backingStoreIsEphemeral = false;
243 auto backingStore = m_server.createBackingStore(identifier);
245 IDBDatabaseInfo databaseInfo;
246 auto error = backingStore->getOrEstablishDatabaseInfo(databaseInfo);
248 LOG_ERROR("Error getting database info from database %s that we are trying to delete", identifier.debugString().utf8().data());
250 deletedVersion = databaseInfo.version();
251 backingStore->deleteBackingStore();
254 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didDeleteBackingStore, deletedVersion));
257 void UniqueIDBDatabase::performUnconditionalDeleteBackingStore()
259 ASSERT(!isMainThread());
260 LOG(IndexedDB, "(db) UniqueIDBDatabase::performUnconditionalDeleteBackingStore");
265 m_backingStore->deleteBackingStore();
266 m_backingStore = nullptr;
267 m_backingStoreSupportsSimultaneousTransactions = false;
268 m_backingStoreIsEphemeral = false;
271 void UniqueIDBDatabase::didDeleteBackingStore(uint64_t deletedVersion)
273 ASSERT(isMainThread());
274 LOG(IndexedDB, "(main) UniqueIDBDatabase::didDeleteBackingStore");
276 ASSERT(!hasAnyPendingCallbacks());
277 ASSERT(!hasUnfinishedTransactions());
278 ASSERT(m_pendingTransactions.isEmpty());
279 ASSERT(m_openDatabaseConnections.isEmpty());
281 // It's possible that the openDBRequest was cancelled from client-side after the delete was already dispatched to the backingstore.
282 // So it's okay if we don't have a currentOpenDBRequest, but if we do it has to be a deleteRequest.
283 ASSERT(!m_currentOpenDBRequest || m_currentOpenDBRequest->isDeleteRequest());
286 m_mostRecentDeletedDatabaseInfo = WTFMove(m_databaseInfo);
288 // If this UniqueIDBDatabase was brought into existence for the purpose of deleting the file on disk,
289 // we won't have a m_mostRecentDeletedDatabaseInfo. In that case, we'll manufacture one using the
290 // passed in deletedVersion argument.
291 if (!m_mostRecentDeletedDatabaseInfo)
292 m_mostRecentDeletedDatabaseInfo = std::make_unique<IDBDatabaseInfo>(m_identifier.databaseName(), deletedVersion);
294 if (m_currentOpenDBRequest) {
295 m_currentOpenDBRequest->notifyDidDeleteDatabase(*m_mostRecentDeletedDatabaseInfo);
296 m_currentOpenDBRequest = nullptr;
299 m_deleteBackingStoreInProgress = false;
301 if (m_clientClosePendingDatabaseConnections.isEmpty() && m_pendingOpenDBRequests.isEmpty()) {
302 m_server.closeUniqueIDBDatabase(*this);
306 invokeOperationAndTransactionTimer();
309 void UniqueIDBDatabase::didPerformUnconditionalDeleteBackingStore()
311 // This function is a placeholder so the database thread can message back to the main thread.
312 ASSERT(m_hardClosedForUserDelete);
315 void UniqueIDBDatabase::handleDatabaseOperations()
317 ASSERT(isMainThread());
318 LOG(IndexedDB, "(main) UniqueIDBDatabase::handleDatabaseOperations - There are %u pending", m_pendingOpenDBRequests.size());
319 ASSERT(!m_hardClosedForUserDelete);
321 if (m_deleteBackingStoreInProgress)
324 if (m_versionChangeDatabaseConnection || m_versionChangeTransaction || m_currentOpenDBRequest) {
325 // We can't start any new open-database operations right now, but we might be able to start handling a delete operation.
326 if (!m_currentOpenDBRequest && !m_pendingOpenDBRequests.isEmpty() && m_pendingOpenDBRequests.first()->isDeleteRequest())
327 m_currentOpenDBRequest = m_pendingOpenDBRequests.takeFirst();
329 // Some operations (such as the first open operation after a delete) require multiple passes to completely handle
330 if (m_currentOpenDBRequest)
331 handleCurrentOperation();
336 if (m_pendingOpenDBRequests.isEmpty())
339 m_currentOpenDBRequest = m_pendingOpenDBRequests.takeFirst();
340 LOG(IndexedDB, "UniqueIDBDatabase::handleDatabaseOperations - Popped an operation, now there are %u pending", m_pendingOpenDBRequests.size());
342 handleCurrentOperation();
345 void UniqueIDBDatabase::handleCurrentOperation()
347 LOG(IndexedDB, "(main) UniqueIDBDatabase::handleCurrentOperation");
348 ASSERT(!m_hardClosedForUserDelete);
349 ASSERT(m_currentOpenDBRequest);
351 RefPtr<UniqueIDBDatabase> protectedThis(this);
353 if (m_currentOpenDBRequest->isOpenRequest())
354 performCurrentOpenOperation();
355 else if (m_currentOpenDBRequest->isDeleteRequest())
356 performCurrentDeleteOperation();
358 ASSERT_NOT_REACHED();
360 if (!m_currentOpenDBRequest)
361 invokeOperationAndTransactionTimer();
364 bool UniqueIDBDatabase::hasAnyOpenConnections() const
366 return !m_openDatabaseConnections.isEmpty();
369 static uint64_t generateUniqueCallbackIdentifier()
371 ASSERT(isMainThread());
372 static uint64_t currentID = 0;
376 uint64_t UniqueIDBDatabase::storeCallbackOrFireError(ErrorCallback callback)
378 if (m_hardClosedForUserDelete) {
379 callback(IDBError::userDeleteError());
383 uint64_t identifier = generateUniqueCallbackIdentifier();
384 ASSERT(!m_errorCallbacks.contains(identifier));
385 m_errorCallbacks.add(identifier, callback);
389 uint64_t UniqueIDBDatabase::storeCallbackOrFireError(KeyDataCallback callback)
391 if (m_hardClosedForUserDelete) {
392 callback(IDBError::userDeleteError(), { });
396 uint64_t identifier = generateUniqueCallbackIdentifier();
397 ASSERT(!m_keyDataCallbacks.contains(identifier));
398 m_keyDataCallbacks.add(identifier, callback);
402 uint64_t UniqueIDBDatabase::storeCallbackOrFireError(GetResultCallback callback)
404 if (m_hardClosedForUserDelete) {
405 callback(IDBError::userDeleteError(), { });
409 uint64_t identifier = generateUniqueCallbackIdentifier();
410 ASSERT(!m_getResultCallbacks.contains(identifier));
411 m_getResultCallbacks.add(identifier, callback);
415 uint64_t UniqueIDBDatabase::storeCallbackOrFireError(GetAllResultsCallback callback)
417 if (m_hardClosedForUserDelete) {
418 callback(IDBError::userDeleteError(), { });
422 uint64_t identifier = generateUniqueCallbackIdentifier();
423 ASSERT(!m_getAllResultsCallbacks.contains(identifier));
424 m_getAllResultsCallbacks.add(identifier, callback);
428 uint64_t UniqueIDBDatabase::storeCallbackOrFireError(CountCallback callback)
430 if (m_hardClosedForUserDelete) {
431 callback(IDBError::userDeleteError(), 0);
435 uint64_t identifier = generateUniqueCallbackIdentifier();
436 ASSERT(!m_countCallbacks.contains(identifier));
437 m_countCallbacks.add(identifier, callback);
441 void UniqueIDBDatabase::handleDelete(IDBConnectionToClient& connection, const IDBRequestData& requestData)
443 LOG(IndexedDB, "(main) UniqueIDBDatabase::handleDelete");
444 ASSERT(!m_hardClosedForUserDelete);
446 m_pendingOpenDBRequests.add(ServerOpenDBRequest::create(connection, requestData));
447 handleDatabaseOperations();
450 void UniqueIDBDatabase::startVersionChangeTransaction()
452 LOG(IndexedDB, "(main) UniqueIDBDatabase::startVersionChangeTransaction");
454 ASSERT(!m_versionChangeTransaction);
455 ASSERT(m_currentOpenDBRequest);
456 ASSERT(m_currentOpenDBRequest->isOpenRequest());
457 ASSERT(m_versionChangeDatabaseConnection);
459 auto operation = WTFMove(m_currentOpenDBRequest);
461 uint64_t requestedVersion = operation->requestData().requestedVersion();
462 if (!requestedVersion)
463 requestedVersion = m_databaseInfo->version() ? m_databaseInfo->version() : 1;
465 addOpenDatabaseConnection(*m_versionChangeDatabaseConnection);
467 m_versionChangeTransaction = &m_versionChangeDatabaseConnection->createVersionChangeTransaction(requestedVersion);
468 m_databaseInfo->setVersion(requestedVersion);
470 m_inProgressTransactions.set(m_versionChangeTransaction->info().identifier(), m_versionChangeTransaction);
471 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::beginTransactionInBackingStore, m_versionChangeTransaction->info()));
473 auto result = IDBResultData::openDatabaseUpgradeNeeded(operation->requestData().requestIdentifier(), *m_versionChangeTransaction);
474 operation->connection().didOpenDatabase(result);
477 void UniqueIDBDatabase::beginTransactionInBackingStore(const IDBTransactionInfo& info)
479 LOG(IndexedDB, "(db) UniqueIDBDatabase::beginTransactionInBackingStore");
480 m_backingStore->beginTransaction(info);
483 void UniqueIDBDatabase::maybeNotifyConnectionsOfVersionChange()
485 ASSERT(m_currentOpenDBRequest);
487 if (m_currentOpenDBRequest->hasNotifiedConnectionsOfVersionChange())
490 uint64_t newVersion = m_currentOpenDBRequest->isOpenRequest() ? m_currentOpenDBRequest->requestData().requestedVersion() : 0;
491 auto requestIdentifier = m_currentOpenDBRequest->requestData().requestIdentifier();
493 LOG(IndexedDB, "(main) UniqueIDBDatabase::notifyConnectionsOfVersionChange - %" PRIu64, newVersion);
495 // 3.3.7 "versionchange" transaction steps
496 // Fire a versionchange event at each connection in m_openDatabaseConnections that is open.
497 // The event must not be fired on connections which has the closePending flag set.
498 HashSet<uint64_t> connectionIdentifiers;
499 for (auto connection : m_openDatabaseConnections) {
500 if (connection->closePending())
503 connection->fireVersionChangeEvent(requestIdentifier, newVersion);
504 connectionIdentifiers.add(connection->identifier());
507 m_currentOpenDBRequest->notifiedConnectionsOfVersionChange(WTFMove(connectionIdentifiers));
510 void UniqueIDBDatabase::notifyCurrentRequestConnectionClosedOrFiredVersionChangeEvent(uint64_t connectionIdentifier)
512 LOG(IndexedDB, "UniqueIDBDatabase::notifyCurrentRequestConnectionClosedOrFiredVersionChangeEvent - %" PRIu64, connectionIdentifier);
514 ASSERT(m_currentOpenDBRequest);
516 m_currentOpenDBRequest->connectionClosedOrFiredVersionChangeEvent(connectionIdentifier);
518 if (m_currentOpenDBRequest->hasConnectionsPendingVersionChangeEvent())
521 if (!hasAnyOpenConnections()) {
522 invokeOperationAndTransactionTimer();
526 if (m_currentOpenDBRequest->hasNotifiedBlocked())
529 // Since all open connections have fired their version change events but not all of them have closed,
530 // this request is officially blocked.
531 m_currentOpenDBRequest->notifyRequestBlocked(m_databaseInfo->version());
534 void UniqueIDBDatabase::didFireVersionChangeEvent(UniqueIDBDatabaseConnection& connection, const IDBResourceIdentifier& requestIdentifier)
536 LOG(IndexedDB, "UniqueIDBDatabase::didFireVersionChangeEvent");
538 if (!m_currentOpenDBRequest)
541 ASSERT_UNUSED(requestIdentifier, m_currentOpenDBRequest->requestData().requestIdentifier() == requestIdentifier);
543 notifyCurrentRequestConnectionClosedOrFiredVersionChangeEvent(connection.identifier());
546 void UniqueIDBDatabase::openDBRequestCancelled(const IDBResourceIdentifier& requestIdentifier)
548 LOG(IndexedDB, "UniqueIDBDatabase::openDBRequestCancelled - %s", requestIdentifier.loggingString().utf8().data());
550 if (m_currentOpenDBRequest && m_currentOpenDBRequest->requestData().requestIdentifier() == requestIdentifier)
551 m_currentOpenDBRequest = nullptr;
553 if (m_versionChangeDatabaseConnection && m_versionChangeDatabaseConnection->openRequestIdentifier() == requestIdentifier) {
554 ASSERT(!m_versionChangeTransaction || m_versionChangeTransaction->databaseConnection().openRequestIdentifier() == requestIdentifier);
555 ASSERT(!m_versionChangeTransaction || &m_versionChangeTransaction->databaseConnection() == m_versionChangeDatabaseConnection);
557 connectionClosedFromClient(*m_versionChangeDatabaseConnection);
560 for (auto& request : m_pendingOpenDBRequests) {
561 if (request->requestData().requestIdentifier() == requestIdentifier) {
562 m_pendingOpenDBRequests.remove(request);
568 void UniqueIDBDatabase::addOpenDatabaseConnection(Ref<UniqueIDBDatabaseConnection>&& connection)
570 ASSERT(!m_openDatabaseConnections.contains(&connection.get()));
571 m_openDatabaseConnections.add(adoptRef(connection.leakRef()));
574 void UniqueIDBDatabase::openBackingStore(const IDBDatabaseIdentifier& identifier)
576 ASSERT(!isMainThread());
577 LOG(IndexedDB, "(db) UniqueIDBDatabase::openBackingStore (%p)", this);
579 ASSERT(!m_backingStore);
580 m_backingStore = m_server.createBackingStore(identifier);
581 m_backingStoreSupportsSimultaneousTransactions = m_backingStore->supportsSimultaneousTransactions();
582 m_backingStoreIsEphemeral = m_backingStore->isEphemeral();
584 IDBDatabaseInfo databaseInfo;
585 auto error = m_backingStore->getOrEstablishDatabaseInfo(databaseInfo);
587 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didOpenBackingStore, databaseInfo, error));
590 void UniqueIDBDatabase::didOpenBackingStore(const IDBDatabaseInfo& info, const IDBError& error)
592 ASSERT(isMainThread());
593 LOG(IndexedDB, "(main) UniqueIDBDatabase::didOpenBackingStore");
595 m_databaseInfo = std::make_unique<IDBDatabaseInfo>(info);
596 m_backingStoreOpenError = error;
598 ASSERT(m_isOpeningBackingStore);
599 m_isOpeningBackingStore = false;
601 handleDatabaseOperations();
604 void UniqueIDBDatabase::createObjectStore(UniqueIDBDatabaseTransaction& transaction, const IDBObjectStoreInfo& info, ErrorCallback callback)
606 ASSERT(isMainThread());
607 LOG(IndexedDB, "(main) UniqueIDBDatabase::createObjectStore");
609 uint64_t callbackID = storeCallbackOrFireError(callback);
613 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performCreateObjectStore, callbackID, transaction.info().identifier(), info));
616 void UniqueIDBDatabase::performCreateObjectStore(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, const IDBObjectStoreInfo& info)
618 ASSERT(!isMainThread());
619 LOG(IndexedDB, "(db) UniqueIDBDatabase::performCreateObjectStore");
621 ASSERT(m_backingStore);
622 m_backingStore->createObjectStore(transactionIdentifier, info);
625 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformCreateObjectStore, callbackIdentifier, error, info));
628 void UniqueIDBDatabase::didPerformCreateObjectStore(uint64_t callbackIdentifier, const IDBError& error, const IDBObjectStoreInfo& info)
630 ASSERT(isMainThread());
631 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformCreateObjectStore");
634 m_databaseInfo->addExistingObjectStore(info);
636 performErrorCallback(callbackIdentifier, error);
639 void UniqueIDBDatabase::deleteObjectStore(UniqueIDBDatabaseTransaction& transaction, const String& objectStoreName, ErrorCallback callback)
641 ASSERT(isMainThread());
642 LOG(IndexedDB, "(main) UniqueIDBDatabase::deleteObjectStore");
644 uint64_t callbackID = storeCallbackOrFireError(callback);
648 auto* info = m_databaseInfo->infoForExistingObjectStore(objectStoreName);
650 performErrorCallback(callbackID, { IDBDatabaseException::UnknownError, ASCIILiteral("Attempt to delete non-existant object store") });
654 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performDeleteObjectStore, callbackID, transaction.info().identifier(), info->identifier()));
657 void UniqueIDBDatabase::performDeleteObjectStore(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, uint64_t objectStoreIdentifier)
659 ASSERT(!isMainThread());
660 LOG(IndexedDB, "(db) UniqueIDBDatabase::performDeleteObjectStore");
662 ASSERT(m_backingStore);
663 m_backingStore->deleteObjectStore(transactionIdentifier, objectStoreIdentifier);
666 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformDeleteObjectStore, callbackIdentifier, error, objectStoreIdentifier));
669 void UniqueIDBDatabase::didPerformDeleteObjectStore(uint64_t callbackIdentifier, const IDBError& error, uint64_t objectStoreIdentifier)
671 ASSERT(isMainThread());
672 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformDeleteObjectStore");
675 m_databaseInfo->deleteObjectStore(objectStoreIdentifier);
677 performErrorCallback(callbackIdentifier, error);
680 void UniqueIDBDatabase::renameObjectStore(UniqueIDBDatabaseTransaction& transaction, uint64_t objectStoreIdentifier, const String& newName, ErrorCallback callback)
682 ASSERT(isMainThread());
683 LOG(IndexedDB, "(main) UniqueIDBDatabase::renameObjectStore");
685 uint64_t callbackID = storeCallbackOrFireError(callback);
689 auto* info = m_databaseInfo->infoForExistingObjectStore(objectStoreIdentifier);
691 performErrorCallback(callbackID, { IDBDatabaseException::UnknownError, ASCIILiteral("Attempt to rename non-existant object store") });
695 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performRenameObjectStore, callbackID, transaction.info().identifier(), objectStoreIdentifier, newName));
698 void UniqueIDBDatabase::performRenameObjectStore(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, uint64_t objectStoreIdentifier, const String& newName)
700 ASSERT(!isMainThread());
701 LOG(IndexedDB, "(db) UniqueIDBDatabase::performRenameObjectStore");
703 ASSERT(m_backingStore);
704 m_backingStore->renameObjectStore(transactionIdentifier, objectStoreIdentifier, newName);
707 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformRenameObjectStore, callbackIdentifier, error, objectStoreIdentifier, newName));
710 void UniqueIDBDatabase::didPerformRenameObjectStore(uint64_t callbackIdentifier, const IDBError& error, uint64_t objectStoreIdentifier, const String& newName)
712 ASSERT(isMainThread());
713 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformRenameObjectStore");
716 m_databaseInfo->renameObjectStore(objectStoreIdentifier, newName);
718 performErrorCallback(callbackIdentifier, error);
721 void UniqueIDBDatabase::clearObjectStore(UniqueIDBDatabaseTransaction& transaction, uint64_t objectStoreIdentifier, ErrorCallback callback)
723 ASSERT(isMainThread());
724 LOG(IndexedDB, "(main) UniqueIDBDatabase::clearObjectStore");
726 uint64_t callbackID = storeCallbackOrFireError(callback);
729 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performClearObjectStore, callbackID, transaction.info().identifier(), objectStoreIdentifier));
732 void UniqueIDBDatabase::performClearObjectStore(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, uint64_t objectStoreIdentifier)
734 ASSERT(!isMainThread());
735 LOG(IndexedDB, "(db) UniqueIDBDatabase::performClearObjectStore");
737 ASSERT(m_backingStore);
738 m_backingStore->clearObjectStore(transactionIdentifier, objectStoreIdentifier);
741 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformClearObjectStore, callbackIdentifier, error));
744 void UniqueIDBDatabase::didPerformClearObjectStore(uint64_t callbackIdentifier, const IDBError& error)
746 ASSERT(isMainThread());
747 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformClearObjectStore");
749 performErrorCallback(callbackIdentifier, error);
752 void UniqueIDBDatabase::createIndex(UniqueIDBDatabaseTransaction& transaction, const IDBIndexInfo& info, ErrorCallback callback)
754 ASSERT(isMainThread());
755 LOG(IndexedDB, "(main) UniqueIDBDatabase::createIndex");
757 uint64_t callbackID = storeCallbackOrFireError(callback);
760 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performCreateIndex, callbackID, transaction.info().identifier(), info));
763 void UniqueIDBDatabase::performCreateIndex(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, const IDBIndexInfo& info)
765 ASSERT(!isMainThread());
766 LOG(IndexedDB, "(db) UniqueIDBDatabase::performCreateIndex");
768 ASSERT(m_backingStore);
769 IDBError error = m_backingStore->createIndex(transactionIdentifier, info);
771 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformCreateIndex, callbackIdentifier, error, info));
774 void UniqueIDBDatabase::didPerformCreateIndex(uint64_t callbackIdentifier, const IDBError& error, const IDBIndexInfo& info)
776 ASSERT(isMainThread());
777 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformCreateIndex");
779 if (error.isNull()) {
780 ASSERT(m_databaseInfo);
781 auto* objectStoreInfo = m_databaseInfo->infoForExistingObjectStore(info.objectStoreIdentifier());
782 ASSERT(objectStoreInfo);
783 objectStoreInfo->addExistingIndex(info);
786 performErrorCallback(callbackIdentifier, error);
789 void UniqueIDBDatabase::deleteIndex(UniqueIDBDatabaseTransaction& transaction, uint64_t objectStoreIdentifier, const String& indexName, ErrorCallback callback)
791 ASSERT(isMainThread());
792 LOG(IndexedDB, "(main) UniqueIDBDatabase::deleteIndex");
794 uint64_t callbackID = storeCallbackOrFireError(callback);
798 auto* objectStoreInfo = m_databaseInfo->infoForExistingObjectStore(objectStoreIdentifier);
799 if (!objectStoreInfo) {
800 performErrorCallback(callbackID, { IDBDatabaseException::UnknownError, ASCIILiteral("Attempt to delete index from non-existant object store") });
804 auto* indexInfo = objectStoreInfo->infoForExistingIndex(indexName);
806 performErrorCallback(callbackID, { IDBDatabaseException::UnknownError, ASCIILiteral("Attempt to delete non-existant index") });
810 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performDeleteIndex, callbackID, transaction.info().identifier(), objectStoreIdentifier, indexInfo->identifier()));
813 void UniqueIDBDatabase::performDeleteIndex(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, uint64_t objectStoreIdentifier, const uint64_t indexIdentifier)
815 ASSERT(!isMainThread());
816 LOG(IndexedDB, "(db) UniqueIDBDatabase::performDeleteIndex");
818 ASSERT(m_backingStore);
819 m_backingStore->deleteIndex(transactionIdentifier, objectStoreIdentifier, indexIdentifier);
822 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformDeleteIndex, callbackIdentifier, error, objectStoreIdentifier, indexIdentifier));
825 void UniqueIDBDatabase::didPerformDeleteIndex(uint64_t callbackIdentifier, const IDBError& error, uint64_t objectStoreIdentifier, uint64_t indexIdentifier)
827 ASSERT(isMainThread());
828 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformDeleteIndex");
830 if (error.isNull()) {
831 auto* objectStoreInfo = m_databaseInfo->infoForExistingObjectStore(objectStoreIdentifier);
833 objectStoreInfo->deleteIndex(indexIdentifier);
836 performErrorCallback(callbackIdentifier, error);
839 void UniqueIDBDatabase::renameIndex(UniqueIDBDatabaseTransaction& transaction, uint64_t objectStoreIdentifier, uint64_t indexIdentifier, const String& newName, ErrorCallback callback)
841 ASSERT(isMainThread());
842 LOG(IndexedDB, "(main) UniqueIDBDatabase::renameIndex");
844 uint64_t callbackID = storeCallbackOrFireError(callback);
848 auto* objectStoreInfo = m_databaseInfo->infoForExistingObjectStore(objectStoreIdentifier);
849 if (!objectStoreInfo) {
850 performErrorCallback(callbackID, { IDBDatabaseException::UnknownError, ASCIILiteral("Attempt to rename index in non-existant object store") });
854 auto* indexInfo = objectStoreInfo->infoForExistingIndex(indexIdentifier);
856 performErrorCallback(callbackID, { IDBDatabaseException::UnknownError, ASCIILiteral("Attempt to rename non-existant index") });
860 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performRenameIndex, callbackID, transaction.info().identifier(), objectStoreIdentifier, indexIdentifier, newName));
863 void UniqueIDBDatabase::performRenameIndex(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, uint64_t objectStoreIdentifier, uint64_t indexIdentifier, const String& newName)
865 ASSERT(!isMainThread());
866 LOG(IndexedDB, "(db) UniqueIDBDatabase::performRenameIndex");
868 ASSERT(m_backingStore);
869 m_backingStore->renameIndex(transactionIdentifier, objectStoreIdentifier, indexIdentifier, newName);
872 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformRenameIndex, callbackIdentifier, error, objectStoreIdentifier, indexIdentifier, newName));
875 void UniqueIDBDatabase::didPerformRenameIndex(uint64_t callbackIdentifier, const IDBError& error, uint64_t objectStoreIdentifier, uint64_t indexIdentifier, const String& newName)
877 ASSERT(isMainThread());
878 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformRenameIndex");
880 if (error.isNull()) {
881 auto* objectStoreInfo = m_databaseInfo->infoForExistingObjectStore(objectStoreIdentifier);
882 ASSERT(objectStoreInfo);
883 if (objectStoreInfo) {
884 auto* indexInfo = objectStoreInfo->infoForExistingIndex(indexIdentifier);
886 indexInfo->rename(newName);
890 performErrorCallback(callbackIdentifier, error);
893 void UniqueIDBDatabase::putOrAdd(const IDBRequestData& requestData, const IDBKeyData& keyData, const IDBValue& value, IndexedDB::ObjectStoreOverwriteMode overwriteMode, KeyDataCallback callback)
895 ASSERT(isMainThread());
896 LOG(IndexedDB, "(main) UniqueIDBDatabase::putOrAdd");
898 uint64_t callbackID = storeCallbackOrFireError(callback);
901 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performPutOrAdd, callbackID, requestData.transactionIdentifier(), requestData.objectStoreIdentifier(), keyData, value, overwriteMode));
904 VM& UniqueIDBDatabase::databaseThreadVM()
906 ASSERT(!isMainThread());
907 static VM* vm = &VM::create().leakRef();
911 ExecState& UniqueIDBDatabase::databaseThreadExecState()
913 ASSERT(!isMainThread());
915 static NeverDestroyed<Strong<JSGlobalObject>> globalObject(databaseThreadVM(), JSGlobalObject::create(databaseThreadVM(), JSGlobalObject::createStructure(databaseThreadVM(), jsNull())));
917 RELEASE_ASSERT(globalObject.get()->globalExec());
918 return *globalObject.get()->globalExec();
921 void UniqueIDBDatabase::performPutOrAdd(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, uint64_t objectStoreIdentifier, const IDBKeyData& keyData, const IDBValue& originalRecordValue, IndexedDB::ObjectStoreOverwriteMode overwriteMode)
923 ASSERT(!isMainThread());
924 LOG(IndexedDB, "(db) UniqueIDBDatabase::performPutOrAdd");
926 ASSERT(m_backingStore);
927 ASSERT(objectStoreIdentifier);
932 auto* objectStoreInfo = m_backingStore->infoForObjectStore(objectStoreIdentifier);
933 if (!objectStoreInfo) {
934 error = IDBError(IDBDatabaseException::InvalidStateError, ASCIILiteral("Object store cannot be found in the backing store"));
935 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformPutOrAdd, callbackIdentifier, error, usedKey));
939 bool usedKeyIsGenerated = false;
940 ScopeGuard generatedKeyResetter;
941 if (objectStoreInfo->autoIncrement() && !keyData.isValid()) {
943 error = m_backingStore->generateKeyNumber(transactionIdentifier, objectStoreIdentifier, keyNumber);
944 if (!error.isNull()) {
945 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformPutOrAdd, callbackIdentifier, error, usedKey));
949 usedKey.setNumberValue(keyNumber);
950 usedKeyIsGenerated = true;
951 generatedKeyResetter.enable([this, transactionIdentifier, objectStoreIdentifier, keyNumber]() {
952 m_backingStore->revertGeneratedKeyNumber(transactionIdentifier, objectStoreIdentifier, keyNumber);
957 if (overwriteMode == IndexedDB::ObjectStoreOverwriteMode::NoOverwrite) {
959 error = m_backingStore->keyExistsInObjectStore(transactionIdentifier, objectStoreIdentifier, usedKey, keyExists);
960 if (error.isNull() && keyExists)
961 error = IDBError(IDBDatabaseException::ConstraintError, ASCIILiteral("Key already exists in the object store"));
963 if (!error.isNull()) {
964 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformPutOrAdd, callbackIdentifier, error, usedKey));
969 // 3.4.1.2 Object Store Storage Operation
970 // If ObjectStore has a key path and the key is autogenerated, then inject the key into the value
971 // using steps to assign a key to a value using a key path.
972 ThreadSafeDataBuffer injectedRecordValue;
973 if (usedKeyIsGenerated && objectStoreInfo->keyPath()) {
974 VM& vm = databaseThreadVM();
975 JSLockHolder locker(vm);
976 auto scope = DECLARE_THROW_SCOPE(vm);
978 auto value = deserializeIDBValueToJSValue(databaseThreadExecState(), originalRecordValue.data());
979 if (value.isUndefined()) {
980 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformPutOrAdd, callbackIdentifier, IDBError(IDBDatabaseException::ConstraintError, ASCIILiteral("Unable to deserialize record value for record key injection")), usedKey));
984 if (!injectIDBKeyIntoScriptValue(databaseThreadExecState(), usedKey, value, objectStoreInfo->keyPath().value())) {
985 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformPutOrAdd, callbackIdentifier, IDBError(IDBDatabaseException::ConstraintError, ASCIILiteral("Unable to inject record key into record value")), usedKey));
989 auto serializedValue = SerializedScriptValue::create(databaseThreadExecState(), value);
990 if (UNLIKELY(scope.exception())) {
991 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformPutOrAdd, callbackIdentifier, IDBError(IDBDatabaseException::ConstraintError, ASCIILiteral("Unable to serialize record value after injecting record key")), usedKey));
995 injectedRecordValue = ThreadSafeDataBuffer::copyVector(serializedValue->data());
998 // 3.4.1 Object Store Storage Operation
999 // ...If a record already exists in store ...
1000 // then remove the record from store using the steps for deleting records from an object store...
1001 // This is important because formally deleting it from from the object store also removes it from the appropriate indexes.
1002 error = m_backingStore->deleteRange(transactionIdentifier, objectStoreIdentifier, usedKey);
1003 if (!error.isNull()) {
1004 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformPutOrAdd, callbackIdentifier, error, usedKey));
1008 if (injectedRecordValue.data())
1009 error = m_backingStore->addRecord(transactionIdentifier, *objectStoreInfo, usedKey, { injectedRecordValue, originalRecordValue.blobURLs(), originalRecordValue.blobFilePaths() });
1011 error = m_backingStore->addRecord(transactionIdentifier, *objectStoreInfo, usedKey, originalRecordValue);
1013 if (!error.isNull()) {
1014 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformPutOrAdd, callbackIdentifier, error, usedKey));
1018 if (overwriteMode != IndexedDB::ObjectStoreOverwriteMode::OverwriteForCursor && objectStoreInfo->autoIncrement() && keyData.type() == IndexedDB::KeyType::Number)
1019 error = m_backingStore->maybeUpdateKeyGeneratorNumber(transactionIdentifier, objectStoreIdentifier, keyData.number());
1021 generatedKeyResetter.disable();
1022 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformPutOrAdd, callbackIdentifier, error, usedKey));
1025 void UniqueIDBDatabase::didPerformPutOrAdd(uint64_t callbackIdentifier, const IDBError& error, const IDBKeyData& resultKey)
1027 ASSERT(isMainThread());
1028 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformPutOrAdd");
1030 performKeyDataCallback(callbackIdentifier, error, resultKey);
1033 void UniqueIDBDatabase::getRecord(const IDBRequestData& requestData, const IDBGetRecordData& getRecordData, GetResultCallback callback)
1035 ASSERT(isMainThread());
1036 LOG(IndexedDB, "(main) UniqueIDBDatabase::getRecord");
1038 uint64_t callbackID = storeCallbackOrFireError(callback);
1042 if (uint64_t indexIdentifier = requestData.indexIdentifier())
1043 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performGetIndexRecord, callbackID, requestData.transactionIdentifier(), requestData.objectStoreIdentifier(), indexIdentifier, requestData.indexRecordType(), getRecordData.keyRangeData));
1045 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performGetRecord, callbackID, requestData.transactionIdentifier(), requestData.objectStoreIdentifier(), getRecordData.keyRangeData));
1048 void UniqueIDBDatabase::getAllRecords(const IDBRequestData& requestData, const IDBGetAllRecordsData& getAllRecordsData, GetAllResultsCallback callback)
1050 ASSERT(isMainThread());
1051 LOG(IndexedDB, "(main) UniqueIDBDatabase::getAllRecords");
1053 uint64_t callbackID = storeCallbackOrFireError(callback);
1057 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performGetAllRecords, callbackID, requestData.transactionIdentifier(), getAllRecordsData));
1060 void UniqueIDBDatabase::performGetRecord(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, uint64_t objectStoreIdentifier, const IDBKeyRangeData& keyRangeData)
1062 ASSERT(!isMainThread());
1063 LOG(IndexedDB, "(db) UniqueIDBDatabase::performGetRecord");
1065 ASSERT(m_backingStore);
1067 IDBGetResult result;
1068 IDBError error = m_backingStore->getRecord(transactionIdentifier, objectStoreIdentifier, keyRangeData, result);
1070 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformGetRecord, callbackIdentifier, error, result));
1073 void UniqueIDBDatabase::performGetIndexRecord(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, uint64_t objectStoreIdentifier, uint64_t indexIdentifier, IndexedDB::IndexRecordType recordType, const IDBKeyRangeData& range)
1075 ASSERT(!isMainThread());
1076 LOG(IndexedDB, "(db) UniqueIDBDatabase::performGetIndexRecord");
1078 ASSERT(m_backingStore);
1080 IDBGetResult result;
1081 IDBError error = m_backingStore->getIndexRecord(transactionIdentifier, objectStoreIdentifier, indexIdentifier, recordType, range, result);
1083 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformGetRecord, callbackIdentifier, error, result));
1086 void UniqueIDBDatabase::didPerformGetRecord(uint64_t callbackIdentifier, const IDBError& error, const IDBGetResult& result)
1088 ASSERT(isMainThread());
1089 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformGetRecord");
1091 performGetResultCallback(callbackIdentifier, error, result);
1094 void UniqueIDBDatabase::performGetAllRecords(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, const IDBGetAllRecordsData& getAllRecordsData)
1096 ASSERT(!isMainThread());
1097 LOG(IndexedDB, "(db) UniqueIDBDatabase::performGetAllRecords");
1099 ASSERT(m_backingStore);
1101 IDBGetAllResult result;
1102 IDBError error = m_backingStore->getAllRecords(transactionIdentifier, getAllRecordsData, result);
1104 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformGetAllRecords, callbackIdentifier, error, WTFMove(result)));
1107 void UniqueIDBDatabase::didPerformGetAllRecords(uint64_t callbackIdentifier, const IDBError& error, const IDBGetAllResult& result)
1109 ASSERT(isMainThread());
1110 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformGetAllRecords");
1112 performGetAllResultsCallback(callbackIdentifier, error, result);
1115 void UniqueIDBDatabase::getCount(const IDBRequestData& requestData, const IDBKeyRangeData& range, CountCallback callback)
1117 ASSERT(isMainThread());
1118 LOG(IndexedDB, "(main) UniqueIDBDatabase::getCount");
1120 uint64_t callbackID = storeCallbackOrFireError(callback);
1123 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performGetCount, callbackID, requestData.transactionIdentifier(), requestData.objectStoreIdentifier(), requestData.indexIdentifier(), range));
1126 void UniqueIDBDatabase::performGetCount(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, uint64_t objectStoreIdentifier, uint64_t indexIdentifier, const IDBKeyRangeData& keyRangeData)
1128 ASSERT(!isMainThread());
1129 LOG(IndexedDB, "(db) UniqueIDBDatabase::performGetCount");
1131 ASSERT(m_backingStore);
1132 ASSERT(objectStoreIdentifier);
1135 IDBError error = m_backingStore->getCount(transactionIdentifier, objectStoreIdentifier, indexIdentifier, keyRangeData, count);
1137 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformGetCount, callbackIdentifier, error, count));
1140 void UniqueIDBDatabase::didPerformGetCount(uint64_t callbackIdentifier, const IDBError& error, uint64_t count)
1142 ASSERT(isMainThread());
1143 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformGetCount");
1145 performCountCallback(callbackIdentifier, error, count);
1148 void UniqueIDBDatabase::deleteRecord(const IDBRequestData& requestData, const IDBKeyRangeData& keyRangeData, ErrorCallback callback)
1150 ASSERT(isMainThread());
1151 LOG(IndexedDB, "(main) UniqueIDBDatabase::deleteRecord");
1153 uint64_t callbackID = storeCallbackOrFireError(callback);
1156 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performDeleteRecord, callbackID, requestData.transactionIdentifier(), requestData.objectStoreIdentifier(), keyRangeData));
1159 void UniqueIDBDatabase::performDeleteRecord(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, uint64_t objectStoreIdentifier, const IDBKeyRangeData& range)
1161 ASSERT(!isMainThread());
1162 LOG(IndexedDB, "(db) UniqueIDBDatabase::performDeleteRecord");
1164 IDBError error = m_backingStore->deleteRange(transactionIdentifier, objectStoreIdentifier, range);
1166 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformDeleteRecord, callbackIdentifier, error));
1169 void UniqueIDBDatabase::didPerformDeleteRecord(uint64_t callbackIdentifier, const IDBError& error)
1171 ASSERT(isMainThread());
1172 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformDeleteRecord");
1174 performErrorCallback(callbackIdentifier, error);
1177 void UniqueIDBDatabase::openCursor(const IDBRequestData& requestData, const IDBCursorInfo& info, GetResultCallback callback)
1179 ASSERT(isMainThread());
1180 LOG(IndexedDB, "(main) UniqueIDBDatabase::openCursor");
1182 uint64_t callbackID = storeCallbackOrFireError(callback);
1185 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performOpenCursor, callbackID, requestData.transactionIdentifier(), info));
1188 void UniqueIDBDatabase::performOpenCursor(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, const IDBCursorInfo& info)
1190 ASSERT(!isMainThread());
1191 LOG(IndexedDB, "(db) UniqueIDBDatabase::performOpenCursor");
1193 IDBGetResult result;
1194 IDBError error = m_backingStore->openCursor(transactionIdentifier, info, result);
1196 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformOpenCursor, callbackIdentifier, error, result));
1199 void UniqueIDBDatabase::didPerformOpenCursor(uint64_t callbackIdentifier, const IDBError& error, const IDBGetResult& result)
1201 ASSERT(isMainThread());
1202 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformOpenCursor");
1204 performGetResultCallback(callbackIdentifier, error, result);
1207 void UniqueIDBDatabase::iterateCursor(const IDBRequestData& requestData, const IDBIterateCursorData& data, GetResultCallback callback)
1209 ASSERT(isMainThread());
1210 LOG(IndexedDB, "(main) UniqueIDBDatabase::iterateCursor");
1212 uint64_t callbackID = storeCallbackOrFireError(callback);
1215 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performIterateCursor, callbackID, requestData.transactionIdentifier(), requestData.cursorIdentifier(), data));
1218 void UniqueIDBDatabase::performIterateCursor(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier, const IDBResourceIdentifier& cursorIdentifier, const IDBIterateCursorData& data)
1220 ASSERT(!isMainThread());
1221 LOG(IndexedDB, "(db) UniqueIDBDatabase::performIterateCursor");
1223 IDBGetResult result;
1224 IDBError error = m_backingStore->iterateCursor(transactionIdentifier, cursorIdentifier, data, result);
1226 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformIterateCursor, callbackIdentifier, error, result));
1229 void UniqueIDBDatabase::didPerformIterateCursor(uint64_t callbackIdentifier, const IDBError& error, const IDBGetResult& result)
1231 ASSERT(isMainThread());
1232 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformIterateCursor");
1234 performGetResultCallback(callbackIdentifier, error, result);
1237 bool UniqueIDBDatabase::prepareToFinishTransaction(UniqueIDBDatabaseTransaction& transaction)
1239 auto takenTransaction = m_inProgressTransactions.take(transaction.info().identifier());
1240 if (!takenTransaction)
1243 ASSERT(!m_finishingTransactions.contains(transaction.info().identifier()));
1244 m_finishingTransactions.set(transaction.info().identifier(), WTFMove(takenTransaction));
1249 void UniqueIDBDatabase::commitTransaction(UniqueIDBDatabaseTransaction& transaction, ErrorCallback callback)
1251 ASSERT(isMainThread());
1252 LOG(IndexedDB, "(main) UniqueIDBDatabase::commitTransaction - %s", transaction.info().identifier().loggingString().utf8().data());
1254 ASSERT(&transaction.databaseConnection().database() == this);
1256 uint64_t callbackID = storeCallbackOrFireError(callback);
1260 if (!prepareToFinishTransaction(transaction)) {
1261 if (!m_openDatabaseConnections.contains(&transaction.databaseConnection())) {
1262 // This database connection is closing or has already closed, so there is no point in messaging back to it about the commit failing.
1263 forgetErrorCallback(callbackID);
1267 performErrorCallback(callbackID, { IDBDatabaseException::UnknownError, ASCIILiteral("Attempt to commit transaction that is already finishing") });
1271 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performCommitTransaction, callbackID, transaction.info().identifier()));
1274 void UniqueIDBDatabase::performCommitTransaction(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier)
1276 ASSERT(!isMainThread());
1277 LOG(IndexedDB, "(db) UniqueIDBDatabase::performCommitTransaction - %s", transactionIdentifier.loggingString().utf8().data());
1279 IDBError error = m_backingStore->commitTransaction(transactionIdentifier);
1280 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformCommitTransaction, callbackIdentifier, error, transactionIdentifier));
1283 void UniqueIDBDatabase::didPerformCommitTransaction(uint64_t callbackIdentifier, const IDBError& error, const IDBResourceIdentifier& transactionIdentifier)
1285 ASSERT(isMainThread());
1286 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformCommitTransaction - %s", transactionIdentifier.loggingString().utf8().data());
1288 performErrorCallback(callbackIdentifier, error);
1290 transactionCompleted(m_finishingTransactions.take(transactionIdentifier));
1293 void UniqueIDBDatabase::abortTransaction(UniqueIDBDatabaseTransaction& transaction, ErrorCallback callback)
1295 ASSERT(isMainThread());
1296 LOG(IndexedDB, "(main) UniqueIDBDatabase::abortTransaction - %s", transaction.info().identifier().loggingString().utf8().data());
1298 ASSERT(&transaction.databaseConnection().database() == this);
1300 uint64_t callbackID = storeCallbackOrFireError(callback);
1304 if (!prepareToFinishTransaction(transaction)) {
1305 if (!m_openDatabaseConnections.contains(&transaction.databaseConnection())) {
1306 // This database connection is closing or has already closed, so there is no point in messaging back to it about the abort failing.
1307 forgetErrorCallback(callbackID);
1311 performErrorCallback(callbackID, { IDBDatabaseException::UnknownError, ASCIILiteral("Attempt to abort transaction that is already finishing") });
1315 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performAbortTransaction, callbackID, transaction.info().identifier()));
1318 void UniqueIDBDatabase::didFinishHandlingVersionChange(UniqueIDBDatabaseConnection& connection, const IDBResourceIdentifier& transactionIdentifier)
1320 ASSERT(isMainThread());
1321 LOG(IndexedDB, "(main) UniqueIDBDatabase::didFinishHandlingVersionChange");
1323 ASSERT_UNUSED(transactionIdentifier, !m_versionChangeTransaction || m_versionChangeTransaction->info().identifier() == transactionIdentifier);
1324 ASSERT_UNUSED(connection, !m_versionChangeDatabaseConnection || m_versionChangeDatabaseConnection.get() == &connection);
1326 m_versionChangeTransaction = nullptr;
1327 m_versionChangeDatabaseConnection = nullptr;
1329 if (m_hardClosedForUserDelete) {
1330 maybeFinishHardClose();
1334 invokeOperationAndTransactionTimer();
1337 void UniqueIDBDatabase::performAbortTransaction(uint64_t callbackIdentifier, const IDBResourceIdentifier& transactionIdentifier)
1339 ASSERT(!isMainThread());
1340 LOG(IndexedDB, "(db) UniqueIDBDatabase::performAbortTransaction - %s", transactionIdentifier.loggingString().utf8().data());
1342 IDBError error = m_backingStore->abortTransaction(transactionIdentifier);
1343 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformAbortTransaction, callbackIdentifier, error, transactionIdentifier));
1346 void UniqueIDBDatabase::didPerformAbortTransaction(uint64_t callbackIdentifier, const IDBError& error, const IDBResourceIdentifier& transactionIdentifier)
1348 ASSERT(isMainThread());
1349 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformAbortTransaction - %s", transactionIdentifier.loggingString().utf8().data());
1351 auto transaction = m_finishingTransactions.take(transactionIdentifier);
1352 ASSERT(transaction);
1354 if (m_versionChangeTransaction && m_versionChangeTransaction->info().identifier() == transactionIdentifier) {
1355 ASSERT(m_versionChangeTransaction == transaction);
1356 ASSERT(!m_versionChangeDatabaseConnection || &m_versionChangeTransaction->databaseConnection() == m_versionChangeDatabaseConnection);
1357 ASSERT(m_versionChangeTransaction->originalDatabaseInfo());
1358 m_databaseInfo = std::make_unique<IDBDatabaseInfo>(*m_versionChangeTransaction->originalDatabaseInfo());
1361 performErrorCallback(callbackIdentifier, error);
1363 transactionCompleted(WTFMove(transaction));
1366 void UniqueIDBDatabase::transactionDestroyed(UniqueIDBDatabaseTransaction& transaction)
1368 if (m_versionChangeTransaction == &transaction)
1369 m_versionChangeTransaction = nullptr;
1372 void UniqueIDBDatabase::connectionClosedFromClient(UniqueIDBDatabaseConnection& connection)
1374 ASSERT(isMainThread());
1375 LOG(IndexedDB, "(main) UniqueIDBDatabase::connectionClosedFromClient - %s (%" PRIu64 ")", connection.openRequestIdentifier().loggingString().utf8().data(), connection.identifier());
1377 Ref<UniqueIDBDatabaseConnection> protectedConnection(connection);
1378 m_openDatabaseConnections.remove(&connection);
1380 if (m_versionChangeDatabaseConnection == &connection) {
1381 if (m_versionChangeTransaction) {
1382 m_clientClosePendingDatabaseConnections.add(WTFMove(m_versionChangeDatabaseConnection));
1384 auto transactionIdentifier = m_versionChangeTransaction->info().identifier();
1385 if (m_inProgressTransactions.contains(transactionIdentifier)) {
1386 ASSERT(!m_finishingTransactions.contains(transactionIdentifier));
1387 connection.abortTransactionWithoutCallback(*m_versionChangeTransaction);
1393 m_versionChangeDatabaseConnection = nullptr;
1396 Deque<RefPtr<UniqueIDBDatabaseTransaction>> pendingTransactions;
1397 while (!m_pendingTransactions.isEmpty()) {
1398 auto transaction = m_pendingTransactions.takeFirst();
1399 if (&transaction->databaseConnection() != &connection)
1400 pendingTransactions.append(WTFMove(transaction));
1403 if (!pendingTransactions.isEmpty())
1404 m_pendingTransactions.swap(pendingTransactions);
1406 Deque<RefPtr<UniqueIDBDatabaseTransaction>> transactionsToAbort;
1407 for (auto& transaction : m_inProgressTransactions.values()) {
1408 if (&transaction->databaseConnection() == &connection)
1409 transactionsToAbort.append(transaction);
1412 for (auto& transaction : transactionsToAbort)
1413 transaction->abortWithoutCallback();
1415 if (m_currentOpenDBRequest)
1416 notifyCurrentRequestConnectionClosedOrFiredVersionChangeEvent(connection.identifier());
1418 if (connection.hasNonFinishedTransactions()) {
1419 m_clientClosePendingDatabaseConnections.add(WTFMove(protectedConnection));
1423 if (m_hardClosedForUserDelete) {
1424 maybeFinishHardClose();
1428 // Now that a database connection has closed, previously blocked operations might be runnable.
1429 invokeOperationAndTransactionTimer();
1432 void UniqueIDBDatabase::connectionClosedFromServer(UniqueIDBDatabaseConnection& connection)
1434 ASSERT(isMainThread());
1435 LOG(IndexedDB, "UniqueIDBDatabase::connectionClosedFromServer - %s (%" PRIu64 ")", connection.openRequestIdentifier().loggingString().utf8().data(), connection.identifier());
1437 if (m_clientClosePendingDatabaseConnections.contains(&connection)) {
1438 ASSERT(!m_openDatabaseConnections.contains(&connection));
1439 ASSERT(!m_serverClosePendingDatabaseConnections.contains(&connection));
1443 Ref<UniqueIDBDatabaseConnection> protectedConnection(connection);
1444 m_openDatabaseConnections.remove(&connection);
1446 connection.connectionToClient().didCloseFromServer(connection, IDBError::userDeleteError());
1448 m_serverClosePendingDatabaseConnections.add(WTFMove(protectedConnection));
1451 void UniqueIDBDatabase::confirmDidCloseFromServer(UniqueIDBDatabaseConnection& connection)
1453 ASSERT(isMainThread());
1454 LOG(IndexedDB, "UniqueIDBDatabase::confirmDidCloseFromServer - %s (%" PRIu64 ")", connection.openRequestIdentifier().loggingString().utf8().data(), connection.identifier());
1456 ASSERT(m_serverClosePendingDatabaseConnections.contains(&connection));
1457 m_serverClosePendingDatabaseConnections.remove(&connection);
1460 void UniqueIDBDatabase::enqueueTransaction(Ref<UniqueIDBDatabaseTransaction>&& transaction)
1462 LOG(IndexedDB, "UniqueIDBDatabase::enqueueTransaction - %s", transaction->info().loggingString().utf8().data());
1463 ASSERT(!m_hardClosedForUserDelete);
1465 ASSERT(transaction->info().mode() != IDBTransactionMode::Versionchange);
1467 m_pendingTransactions.append(WTFMove(transaction));
1469 invokeOperationAndTransactionTimer();
1472 bool UniqueIDBDatabase::isCurrentlyInUse() const
1474 return !m_openDatabaseConnections.isEmpty() || !m_clientClosePendingDatabaseConnections.isEmpty() || !m_pendingOpenDBRequests.isEmpty() || m_currentOpenDBRequest || m_versionChangeDatabaseConnection || m_versionChangeTransaction || m_isOpeningBackingStore || m_deleteBackingStoreInProgress;
1477 bool UniqueIDBDatabase::hasUnfinishedTransactions() const
1479 return !m_inProgressTransactions.isEmpty() || !m_finishingTransactions.isEmpty();
1482 void UniqueIDBDatabase::invokeOperationAndTransactionTimer()
1484 LOG(IndexedDB, "UniqueIDBDatabase::invokeOperationAndTransactionTimer()");
1485 ASSERT(!m_hardClosedForUserDelete);
1487 if (!m_operationAndTransactionTimer.isActive())
1488 m_operationAndTransactionTimer.startOneShot(0);
1491 void UniqueIDBDatabase::operationAndTransactionTimerFired()
1493 LOG(IndexedDB, "(main) UniqueIDBDatabase::operationAndTransactionTimerFired");
1494 ASSERT(!m_hardClosedForUserDelete);
1496 RefPtr<UniqueIDBDatabase> protectedThis(this);
1498 // This UniqueIDBDatabase might be no longer in use by any web page.
1499 // Assuming it is not ephemeral, the server should now close it to free up resources.
1500 if (!m_backingStoreIsEphemeral && !isCurrentlyInUse()) {
1501 ASSERT(m_pendingTransactions.isEmpty());
1502 ASSERT(!hasUnfinishedTransactions());
1503 m_server.closeUniqueIDBDatabase(*this);
1507 // The current operation might require multiple attempts to handle, so try to
1508 // make further progress on it now.
1509 if (m_currentOpenDBRequest)
1510 handleCurrentOperation();
1512 if (!m_currentOpenDBRequest)
1513 handleDatabaseOperations();
1515 bool hadDeferredTransactions = false;
1516 auto transaction = takeNextRunnableTransaction(hadDeferredTransactions);
1519 m_inProgressTransactions.set(transaction->info().identifier(), transaction);
1520 for (auto objectStore : transaction->objectStoreIdentifiers()) {
1521 m_objectStoreTransactionCounts.add(objectStore);
1522 if (!transaction->isReadOnly()) {
1523 m_objectStoreWriteTransactions.add(objectStore);
1524 ASSERT(m_objectStoreTransactionCounts.count(objectStore) == 1);
1528 activateTransactionInBackingStore(*transaction);
1530 // If no transactions were deferred, it's possible we can start another transaction right now.
1531 if (!hadDeferredTransactions)
1532 invokeOperationAndTransactionTimer();
1536 void UniqueIDBDatabase::activateTransactionInBackingStore(UniqueIDBDatabaseTransaction& transaction)
1538 LOG(IndexedDB, "(main) UniqueIDBDatabase::activateTransactionInBackingStore");
1540 RefPtr<UniqueIDBDatabase> protectedThis(this);
1541 RefPtr<UniqueIDBDatabaseTransaction> refTransaction(&transaction);
1543 auto callback = [this, protectedThis, refTransaction](const IDBError& error) {
1544 refTransaction->didActivateInBackingStore(error);
1547 uint64_t callbackID = storeCallbackOrFireError(callback);
1550 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performActivateTransactionInBackingStore, callbackID, transaction.info()));
1553 void UniqueIDBDatabase::performActivateTransactionInBackingStore(uint64_t callbackIdentifier, const IDBTransactionInfo& info)
1555 LOG(IndexedDB, "(db) UniqueIDBDatabase::performActivateTransactionInBackingStore");
1557 IDBError error = m_backingStore->beginTransaction(info);
1558 postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::didPerformActivateTransactionInBackingStore, callbackIdentifier, error));
1561 void UniqueIDBDatabase::didPerformActivateTransactionInBackingStore(uint64_t callbackIdentifier, const IDBError& error)
1563 LOG(IndexedDB, "(main) UniqueIDBDatabase::didPerformActivateTransactionInBackingStore");
1565 invokeOperationAndTransactionTimer();
1567 performErrorCallback(callbackIdentifier, error);
1570 template<typename T> bool scopesOverlap(const T& aScopes, const Vector<uint64_t>& bScopes)
1572 for (auto scope : bScopes) {
1573 if (aScopes.contains(scope))
1580 RefPtr<UniqueIDBDatabaseTransaction> UniqueIDBDatabase::takeNextRunnableTransaction(bool& hadDeferredTransactions)
1582 hadDeferredTransactions = false;
1584 if (m_pendingTransactions.isEmpty())
1587 if (!m_backingStoreSupportsSimultaneousTransactions && hasUnfinishedTransactions()) {
1588 LOG(IndexedDB, "UniqueIDBDatabase::takeNextRunnableTransaction - Backing store only supports 1 transaction, and we already have 1");
1592 Deque<RefPtr<UniqueIDBDatabaseTransaction>> deferredTransactions;
1593 RefPtr<UniqueIDBDatabaseTransaction> currentTransaction;
1595 HashSet<uint64_t> deferredReadWriteScopes;
1597 while (!m_pendingTransactions.isEmpty()) {
1598 currentTransaction = m_pendingTransactions.takeFirst();
1600 switch (currentTransaction->info().mode()) {
1601 case IDBTransactionMode::Readonly: {
1602 bool hasOverlappingScopes = scopesOverlap(deferredReadWriteScopes, currentTransaction->objectStoreIdentifiers());
1603 hasOverlappingScopes |= scopesOverlap(m_objectStoreWriteTransactions, currentTransaction->objectStoreIdentifiers());
1605 if (hasOverlappingScopes)
1606 deferredTransactions.append(WTFMove(currentTransaction));
1610 case IDBTransactionMode::Readwrite: {
1611 bool hasOverlappingScopes = scopesOverlap(m_objectStoreTransactionCounts, currentTransaction->objectStoreIdentifiers());
1612 hasOverlappingScopes |= scopesOverlap(deferredReadWriteScopes, currentTransaction->objectStoreIdentifiers());
1614 if (hasOverlappingScopes) {
1615 for (auto objectStore : currentTransaction->objectStoreIdentifiers())
1616 deferredReadWriteScopes.add(objectStore);
1617 deferredTransactions.append(WTFMove(currentTransaction));
1622 case IDBTransactionMode::Versionchange:
1623 // Version change transactions should never be scheduled in the traditional manner.
1624 RELEASE_ASSERT_NOT_REACHED();
1627 // If we didn't defer the currentTransaction above, it can be run now.
1628 if (currentTransaction)
1632 hadDeferredTransactions = !deferredTransactions.isEmpty();
1633 if (!hadDeferredTransactions)
1634 return currentTransaction;
1636 // Prepend the deferred transactions back on the beginning of the deque for future scheduling passes.
1637 while (!deferredTransactions.isEmpty())
1638 m_pendingTransactions.prepend(deferredTransactions.takeLast());
1640 return currentTransaction;
1643 void UniqueIDBDatabase::transactionCompleted(RefPtr<UniqueIDBDatabaseTransaction>&& transaction)
1645 ASSERT(transaction);
1646 ASSERT(!m_inProgressTransactions.contains(transaction->info().identifier()));
1647 ASSERT(!m_finishingTransactions.contains(transaction->info().identifier()));
1649 for (auto objectStore : transaction->objectStoreIdentifiers()) {
1650 if (!transaction->isReadOnly()) {
1651 m_objectStoreWriteTransactions.remove(objectStore);
1652 ASSERT(m_objectStoreTransactionCounts.count(objectStore) == 1);
1654 m_objectStoreTransactionCounts.remove(objectStore);
1657 if (!transaction->databaseConnection().hasNonFinishedTransactions())
1658 m_clientClosePendingDatabaseConnections.remove(&transaction->databaseConnection());
1660 if (m_versionChangeTransaction == transaction)
1661 m_versionChangeTransaction = nullptr;
1663 // It's possible that this database had its backing store deleted but there were a few outstanding asynchronous operations.
1664 // If this transaction completing was the last of those operations, we can finally delete this UniqueIDBDatabase.
1665 if (m_clientClosePendingDatabaseConnections.isEmpty() && m_pendingOpenDBRequests.isEmpty() && !m_databaseInfo) {
1666 m_server.closeUniqueIDBDatabase(*this);
1670 // Previously blocked operations might be runnable.
1671 if (!m_hardClosedForUserDelete)
1672 invokeOperationAndTransactionTimer();
1674 maybeFinishHardClose();
1677 void UniqueIDBDatabase::postDatabaseTask(CrossThreadTask&& task)
1679 ASSERT(isMainThread());
1680 m_databaseQueue.append(WTFMove(task));
1681 ++m_queuedTaskCount;
1683 m_server.postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::executeNextDatabaseTask));
1686 void UniqueIDBDatabase::postDatabaseTaskReply(CrossThreadTask&& task)
1688 ASSERT(!isMainThread());
1689 m_databaseReplyQueue.append(WTFMove(task));
1690 ++m_queuedTaskCount;
1692 m_server.postDatabaseTaskReply(createCrossThreadTask(*this, &UniqueIDBDatabase::executeNextDatabaseTaskReply));
1695 void UniqueIDBDatabase::executeNextDatabaseTask()
1697 ASSERT(!isMainThread());
1698 ASSERT(m_queuedTaskCount);
1700 auto task = m_databaseQueue.tryGetMessage();
1703 // Performing the task might end up removing the last reference to this.
1704 Ref<UniqueIDBDatabase> protectedThis(*this);
1706 task->performTask();
1707 --m_queuedTaskCount;
1709 // Release the ref in the main thread to ensure it's deleted there as expected in case of being the last reference.
1710 callOnMainThread([protectedThis = WTFMove(protectedThis)] {
1714 void UniqueIDBDatabase::executeNextDatabaseTaskReply()
1716 ASSERT(isMainThread());
1717 ASSERT(m_queuedTaskCount);
1719 auto task = m_databaseReplyQueue.tryGetMessage();
1722 // Performing the task might end up removing the last reference to this.
1723 Ref<UniqueIDBDatabase> protectedThis(*this);
1725 task->performTask();
1726 --m_queuedTaskCount;
1728 // If this database was force closed (e.g. for a user delete) and there are no more
1729 // cleanup tasks left, delete this.
1730 maybeFinishHardClose();
1733 void UniqueIDBDatabase::maybeFinishHardClose()
1735 if (m_hardCloseProtector && isDoneWithHardClose()) {
1736 callOnMainThread([this] {
1737 ASSERT(isDoneWithHardClose());
1738 m_hardCloseProtector = nullptr;
1743 bool UniqueIDBDatabase::isDoneWithHardClose()
1745 return !m_queuedTaskCount && m_clientClosePendingDatabaseConnections.isEmpty() && m_serverClosePendingDatabaseConnections.isEmpty();
1748 static void errorOpenDBRequestForUserDelete(ServerOpenDBRequest& request)
1750 auto result = IDBResultData::error(request.requestData().requestIdentifier(), IDBError::userDeleteError());
1751 if (request.isOpenRequest())
1752 request.connection().didOpenDatabase(result);
1754 request.connection().didDeleteDatabase(result);
1757 void UniqueIDBDatabase::immediateCloseForUserDelete()
1759 LOG(IndexedDB, "UniqueIDBDatabase::immediateCloseForUserDelete - Cancelling (%i, %i, %i, %i) callbacks", m_errorCallbacks.size(), m_keyDataCallbacks.size(), m_getResultCallbacks.size(), m_countCallbacks.size());
1761 // Error out all transactions
1762 Vector<IDBResourceIdentifier> inProgressIdentifiers;
1763 copyKeysToVector(m_inProgressTransactions, inProgressIdentifiers);
1764 for (auto& identifier : inProgressIdentifiers)
1765 m_inProgressTransactions.get(identifier)->abortWithoutCallback();
1767 ASSERT(m_inProgressTransactions.isEmpty());
1769 m_pendingTransactions.clear();
1770 m_objectStoreTransactionCounts.clear();
1771 m_objectStoreWriteTransactions.clear();
1773 // Error out all pending callbacks
1774 Vector<uint64_t> callbackIdentifiers;
1775 IDBError error = IDBError::userDeleteError();
1777 IDBGetResult getResult;
1779 copyKeysToVector(m_errorCallbacks, callbackIdentifiers);
1780 for (auto identifier : callbackIdentifiers)
1781 performErrorCallback(identifier, error);
1783 callbackIdentifiers.clear();
1784 copyKeysToVector(m_keyDataCallbacks, callbackIdentifiers);
1785 for (auto identifier : callbackIdentifiers)
1786 performKeyDataCallback(identifier, error, keyData);
1788 callbackIdentifiers.clear();
1789 copyKeysToVector(m_getResultCallbacks, callbackIdentifiers);
1790 for (auto identifier : callbackIdentifiers)
1791 performGetResultCallback(identifier, error, getResult);
1793 callbackIdentifiers.clear();
1794 copyKeysToVector(m_countCallbacks, callbackIdentifiers);
1795 for (auto identifier : callbackIdentifiers)
1796 performCountCallback(identifier, error, 0);
1798 // Error out all IDBOpenDBRequests
1799 if (m_currentOpenDBRequest) {
1800 errorOpenDBRequestForUserDelete(*m_currentOpenDBRequest);
1801 m_currentOpenDBRequest = nullptr;
1804 for (auto& request : m_pendingOpenDBRequests)
1805 errorOpenDBRequestForUserDelete(*request);
1807 m_pendingOpenDBRequests.clear();
1809 // Close all open connections
1810 ListHashSet<RefPtr<UniqueIDBDatabaseConnection>> openDatabaseConnections = m_openDatabaseConnections;
1811 for (auto& connection : openDatabaseConnections)
1812 connectionClosedFromServer(*connection);
1814 // Cancel the operation timer
1815 m_operationAndTransactionTimer.stop();
1817 // Set up the database to remain alive-but-inert until all of its background activity finishes and all
1818 // database connections confirm that they have closed.
1819 m_hardClosedForUserDelete = true;
1820 m_hardCloseProtector = this;
1822 // Have the database unconditionally delete itself on the database task queue.
1823 postDatabaseTask(createCrossThreadTask(*this, &UniqueIDBDatabase::performUnconditionalDeleteBackingStore));
1825 // Remove the database from the IDBServer's set of open databases.
1826 // If there is no in-progress background thread activity for this database, it will be deleted here.
1827 m_server.closeUniqueIDBDatabase(*this);
1830 void UniqueIDBDatabase::performErrorCallback(uint64_t callbackIdentifier, const IDBError& error)
1832 auto callback = m_errorCallbacks.take(callbackIdentifier);
1833 ASSERT(callback || m_hardClosedForUserDelete);
1838 void UniqueIDBDatabase::performKeyDataCallback(uint64_t callbackIdentifier, const IDBError& error, const IDBKeyData& resultKey)
1840 auto callback = m_keyDataCallbacks.take(callbackIdentifier);
1841 ASSERT(callback || m_hardClosedForUserDelete);
1843 callback(error, resultKey);
1846 void UniqueIDBDatabase::performGetResultCallback(uint64_t callbackIdentifier, const IDBError& error, const IDBGetResult& resultData)
1848 auto callback = m_getResultCallbacks.take(callbackIdentifier);
1849 ASSERT(callback || m_hardClosedForUserDelete);
1851 callback(error, resultData);
1854 void UniqueIDBDatabase::performGetAllResultsCallback(uint64_t callbackIdentifier, const IDBError& error, const IDBGetAllResult& resultData)
1856 auto callback = m_getAllResultsCallbacks.take(callbackIdentifier);
1857 ASSERT(callback || m_hardClosedForUserDelete);
1859 callback(error, resultData);
1862 void UniqueIDBDatabase::performCountCallback(uint64_t callbackIdentifier, const IDBError& error, uint64_t count)
1864 auto callback = m_countCallbacks.take(callbackIdentifier);
1865 ASSERT(callback || m_hardClosedForUserDelete);
1867 callback(error, count);
1870 void UniqueIDBDatabase::forgetErrorCallback(uint64_t callbackIdentifier)
1872 ASSERT(m_errorCallbacks.contains(callbackIdentifier));
1873 m_errorCallbacks.remove(callbackIdentifier);
1876 } // namespace IDBServer
1877 } // namespace WebCore
1879 #endif // ENABLE(INDEXED_DATABASE)