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 "IDBDatabase.h"
29 #if ENABLE(INDEXED_DATABASE)
31 #include "DOMStringList.h"
32 #include "EventNames.h"
33 #include "EventQueue.h"
34 #include "IDBConnectionProxy.h"
35 #include "IDBConnectionToServer.h"
36 #include "IDBDatabaseException.h"
38 #include "IDBObjectStore.h"
39 #include "IDBOpenDBRequest.h"
40 #include "IDBResultData.h"
41 #include "IDBTransaction.h"
42 #include "IDBVersionChangeEvent.h"
44 #include "ScriptExecutionContext.h"
48 Ref<IDBDatabase> IDBDatabase::create(ScriptExecutionContext& context, IDBClient::IDBConnectionProxy& connectionProxy, const IDBResultData& resultData)
50 return adoptRef(*new IDBDatabase(context, connectionProxy, resultData));
53 IDBDatabase::IDBDatabase(ScriptExecutionContext& context, IDBClient::IDBConnectionProxy& connectionProxy, const IDBResultData& resultData)
54 : IDBActiveDOMObject(&context)
55 , m_connectionProxy(connectionProxy)
56 , m_info(resultData.databaseInfo())
57 , m_databaseConnectionIdentifier(resultData.databaseConnectionIdentifier())
58 , m_eventNames(eventNames())
60 LOG(IndexedDB, "IDBDatabase::IDBDatabase - Creating database %s with version %" PRIu64 " connection %" PRIu64 " (%p)", m_info.name().utf8().data(), m_info.version(), m_databaseConnectionIdentifier, this);
62 m_connectionProxy->registerDatabaseConnection(*this);
65 IDBDatabase::~IDBDatabase()
67 ASSERT(currentThread() == originThreadID());
69 if (!m_closedInServer)
70 m_connectionProxy->databaseConnectionClosed(*this);
72 m_connectionProxy->unregisterDatabaseConnection(*this);
75 bool IDBDatabase::hasPendingActivity() const
77 ASSERT(currentThread() == originThreadID() || mayBeGCThread());
82 if (!m_activeTransactions.isEmpty() || !m_committingTransactions.isEmpty() || !m_abortingTransactions.isEmpty())
85 return hasEventListeners(m_eventNames.abortEvent) || hasEventListeners(m_eventNames.errorEvent) || hasEventListeners(m_eventNames.versionchangeEvent);
88 const String IDBDatabase::name() const
90 ASSERT(currentThread() == originThreadID());
94 uint64_t IDBDatabase::version() const
96 ASSERT(currentThread() == originThreadID());
97 return m_info.version();
100 RefPtr<DOMStringList> IDBDatabase::objectStoreNames() const
102 ASSERT(currentThread() == originThreadID());
104 RefPtr<DOMStringList> objectStoreNames = DOMStringList::create();
105 for (auto& name : m_info.objectStoreNames())
106 objectStoreNames->append(name);
107 objectStoreNames->sort();
108 return objectStoreNames;
111 void IDBDatabase::renameObjectStore(IDBObjectStore& objectStore, const String& newName)
113 ASSERT(currentThread() == originThreadID());
114 ASSERT(m_versionChangeTransaction);
115 ASSERT(m_info.hasObjectStore(objectStore.info().name()));
117 m_info.renameObjectStore(objectStore.info().identifier(), newName);
119 m_versionChangeTransaction->renameObjectStore(objectStore, newName);
122 void IDBDatabase::renameIndex(IDBIndex& index, const String& newName)
124 ASSERT(currentThread() == originThreadID());
125 ASSERT(m_versionChangeTransaction);
126 ASSERT(m_info.hasObjectStore(index.objectStore().info().name()));
127 ASSERT(m_info.infoForExistingObjectStore(index.objectStore().info().name())->hasIndex(index.info().name()));
129 m_info.infoForExistingObjectStore(index.objectStore().info().name())->infoForExistingIndex(index.info().identifier())->rename(newName);
131 m_versionChangeTransaction->renameIndex(index, newName);
134 ExceptionOr<Ref<IDBObjectStore>> IDBDatabase::createObjectStore(const String& name, ObjectStoreParameters&& parameters)
136 LOG(IndexedDB, "IDBDatabase::createObjectStore - (%s %s)", m_info.name().utf8().data(), name.utf8().data());
138 ASSERT(currentThread() == originThreadID());
139 ASSERT(!m_versionChangeTransaction || m_versionChangeTransaction->isVersionChange());
141 if (!m_versionChangeTransaction)
142 return Exception { IDBDatabaseException::InvalidStateError, ASCIILiteral("Failed to execute 'createObjectStore' on 'IDBDatabase': The database is not running a version change transaction.") };
144 if (!m_versionChangeTransaction->isActive())
145 return Exception { IDBDatabaseException::TransactionInactiveError };
147 if (m_info.hasObjectStore(name))
148 return Exception { IDBDatabaseException::ConstraintError, ASCIILiteral("Failed to execute 'createObjectStore' on 'IDBDatabase': An object store with the specified name already exists.") };
150 auto& keyPath = parameters.keyPath;
151 if (keyPath && !isIDBKeyPathValid(keyPath.value()))
152 return Exception { IDBDatabaseException::SyntaxError, ASCIILiteral("Failed to execute 'createObjectStore' on 'IDBDatabase': The keyPath option is not a valid key path.") };
154 if (keyPath && parameters.autoIncrement && ((WTF::holds_alternative<String>(keyPath.value()) && WTF::get<String>(keyPath.value()).isEmpty()) || WTF::holds_alternative<Vector<String>>(keyPath.value())))
155 return Exception { IDBDatabaseException::InvalidAccessError, ASCIILiteral("Failed to execute 'createObjectStore' on 'IDBDatabase': The autoIncrement option was set but the keyPath option was empty or an array.") };
157 // Install the new ObjectStore into the connection's metadata.
158 auto info = m_info.createNewObjectStore(name, WTFMove(keyPath), parameters.autoIncrement);
160 // Create the actual IDBObjectStore from the transaction, which also schedules the operation server side.
161 return m_versionChangeTransaction->createObjectStore(info);
164 ExceptionOr<Ref<IDBTransaction>> IDBDatabase::transaction(StringOrVectorOfStrings&& storeNames, IDBTransactionMode mode)
166 LOG(IndexedDB, "IDBDatabase::transaction");
168 ASSERT(currentThread() == originThreadID());
171 return Exception { IDBDatabaseException::InvalidStateError, ASCIILiteral("Failed to execute 'transaction' on 'IDBDatabase': The database connection is closing.") };
173 Vector<String> objectStores;
174 if (WTF::holds_alternative<Vector<String>>(storeNames))
175 objectStores = WTFMove(WTF::get<Vector<String>>(storeNames));
177 objectStores.append(WTFMove(WTF::get<String>(storeNames)));
179 if (objectStores.isEmpty())
180 return Exception { IDBDatabaseException::InvalidAccessError, ASCIILiteral("Failed to execute 'transaction' on 'IDBDatabase': The storeNames parameter was empty.") };
182 if (mode != IDBTransactionMode::Readonly && mode != IDBTransactionMode::Readwrite)
183 return Exception { TypeError };
185 if (m_versionChangeTransaction && !m_versionChangeTransaction->isFinishedOrFinishing())
186 return Exception { IDBDatabaseException::InvalidStateError, ASCIILiteral("Failed to execute 'transaction' on 'IDBDatabase': A version change transaction is running.") };
188 // It is valid for javascript to pass in a list of object store names with the same name listed twice,
189 // so we need to put them all in a set to get a unique list.
190 HashSet<String> objectStoreSet;
191 for (auto& objectStore : objectStores)
192 objectStoreSet.add(objectStore);
194 objectStores.clear();
195 copyToVector(objectStoreSet, objectStores);
197 for (auto& objectStoreName : objectStores) {
198 if (m_info.hasObjectStore(objectStoreName))
200 return Exception { IDBDatabaseException::NotFoundError, ASCIILiteral("Failed to execute 'transaction' on 'IDBDatabase': One of the specified object stores was not found.") };
203 auto info = IDBTransactionInfo::clientTransaction(m_connectionProxy.get(), objectStores, mode);
204 auto transaction = IDBTransaction::create(*this, info);
206 LOG(IndexedDB, "IDBDatabase::transaction - Added active transaction %s", info.identifier().loggingString().utf8().data());
208 m_activeTransactions.set(info.identifier(), transaction.ptr());
210 return WTFMove(transaction);
213 ExceptionOr<void> IDBDatabase::deleteObjectStore(const String& objectStoreName)
215 LOG(IndexedDB, "IDBDatabase::deleteObjectStore");
217 ASSERT(currentThread() == originThreadID());
219 if (!m_versionChangeTransaction)
220 return Exception { IDBDatabaseException::InvalidStateError, ASCIILiteral("Failed to execute 'deleteObjectStore' on 'IDBDatabase': The database is not running a version change transaction.") };
222 if (!m_versionChangeTransaction->isActive())
223 return Exception { IDBDatabaseException::TransactionInactiveError };
225 if (!m_info.hasObjectStore(objectStoreName))
226 return Exception { IDBDatabaseException::NotFoundError, ASCIILiteral("Failed to execute 'deleteObjectStore' on 'IDBDatabase': The specified object store was not found.") };
228 m_info.deleteObjectStore(objectStoreName);
229 m_versionChangeTransaction->deleteObjectStore(objectStoreName);
234 void IDBDatabase::close()
236 LOG(IndexedDB, "IDBDatabase::close - %" PRIu64, m_databaseConnectionIdentifier);
238 ASSERT(currentThread() == originThreadID());
240 m_closePending = true;
241 maybeCloseInServer();
244 void IDBDatabase::didCloseFromServer(const IDBError& error)
246 LOG(IndexedDB, "IDBDatabase::didCloseFromServer - %" PRIu64, m_databaseConnectionIdentifier);
248 connectionToServerLost(error);
250 m_connectionProxy->confirmDidCloseFromServer(*this);
253 void IDBDatabase::connectionToServerLost(const IDBError& error)
255 LOG(IndexedDB, "IDBDatabase::connectionToServerLost - %" PRIu64, m_databaseConnectionIdentifier);
257 ASSERT(currentThread() == originThreadID());
259 m_closePending = true;
260 m_closedInServer = true;
262 for (auto& transaction : m_activeTransactions.values())
263 transaction->connectionClosedFromServer(error);
265 auto errorEvent = Event::create(m_eventNames.errorEvent, true, false);
266 errorEvent->setTarget(this);
268 if (auto* context = scriptExecutionContext())
269 context->eventQueue().enqueueEvent(WTFMove(errorEvent));
271 auto closeEvent = Event::create(m_eventNames.closeEvent, true, false);
272 closeEvent->setTarget(this);
274 if (auto* context = scriptExecutionContext())
275 context->eventQueue().enqueueEvent(WTFMove(closeEvent));
278 void IDBDatabase::maybeCloseInServer()
280 LOG(IndexedDB, "IDBDatabase::maybeCloseInServer - %" PRIu64, m_databaseConnectionIdentifier);
282 ASSERT(currentThread() == originThreadID());
284 if (m_closedInServer)
287 // 3.3.9 Database closing steps
288 // Wait for all transactions created using this connection to complete.
289 // Once they are complete, this connection is closed.
290 if (!m_activeTransactions.isEmpty())
293 m_closedInServer = true;
294 m_connectionProxy->databaseConnectionClosed(*this);
297 const char* IDBDatabase::activeDOMObjectName() const
299 ASSERT(currentThread() == originThreadID());
300 return "IDBDatabase";
303 bool IDBDatabase::canSuspendForDocumentSuspension() const
305 ASSERT(currentThread() == originThreadID());
307 // FIXME: This value will sometimes be false when database operations are actually in progress.
308 // Such database operations do not yet exist.
312 void IDBDatabase::stop()
314 LOG(IndexedDB, "IDBDatabase::stop - %" PRIu64, m_databaseConnectionIdentifier);
316 ASSERT(currentThread() == originThreadID());
318 removeAllEventListeners();
320 Vector<IDBResourceIdentifier> transactionIdentifiers;
321 transactionIdentifiers.reserveInitialCapacity(m_activeTransactions.size());
323 for (auto& id : m_activeTransactions.keys())
324 transactionIdentifiers.uncheckedAppend(id);
326 for (auto& id : transactionIdentifiers) {
327 IDBTransaction* transaction = m_activeTransactions.get(id);
335 Ref<IDBTransaction> IDBDatabase::startVersionChangeTransaction(const IDBTransactionInfo& info, IDBOpenDBRequest& request)
337 LOG(IndexedDB, "IDBDatabase::startVersionChangeTransaction %s", info.identifier().loggingString().utf8().data());
339 ASSERT(currentThread() == originThreadID());
340 ASSERT(!m_versionChangeTransaction);
341 ASSERT(info.mode() == IDBTransactionMode::Versionchange);
342 ASSERT(!m_closePending);
343 ASSERT(scriptExecutionContext());
345 Ref<IDBTransaction> transaction = IDBTransaction::create(*this, info, request);
346 m_versionChangeTransaction = &transaction.get();
348 m_activeTransactions.set(transaction->info().identifier(), &transaction.get());
353 void IDBDatabase::didStartTransaction(IDBTransaction& transaction)
355 LOG(IndexedDB, "IDBDatabase::didStartTransaction %s", transaction.info().identifier().loggingString().utf8().data());
356 ASSERT(!m_versionChangeTransaction);
357 ASSERT(currentThread() == originThreadID());
359 // It is possible for the client to have aborted a transaction before the server replies back that it has started.
360 if (m_abortingTransactions.contains(transaction.info().identifier()))
363 m_activeTransactions.set(transaction.info().identifier(), &transaction);
366 void IDBDatabase::willCommitTransaction(IDBTransaction& transaction)
368 LOG(IndexedDB, "IDBDatabase::willCommitTransaction %s", transaction.info().identifier().loggingString().utf8().data());
370 ASSERT(currentThread() == originThreadID());
372 auto refTransaction = m_activeTransactions.take(transaction.info().identifier());
373 ASSERT(refTransaction);
374 m_committingTransactions.set(transaction.info().identifier(), WTFMove(refTransaction));
377 void IDBDatabase::didCommitTransaction(IDBTransaction& transaction)
379 LOG(IndexedDB, "IDBDatabase::didCommitTransaction %s", transaction.info().identifier().loggingString().utf8().data());
381 ASSERT(currentThread() == originThreadID());
383 if (m_versionChangeTransaction == &transaction)
384 m_info.setVersion(transaction.info().newVersion());
386 didCommitOrAbortTransaction(transaction);
389 void IDBDatabase::willAbortTransaction(IDBTransaction& transaction)
391 LOG(IndexedDB, "IDBDatabase::willAbortTransaction %s", transaction.info().identifier().loggingString().utf8().data());
393 ASSERT(currentThread() == originThreadID());
395 auto refTransaction = m_activeTransactions.take(transaction.info().identifier());
397 refTransaction = m_committingTransactions.take(transaction.info().identifier());
399 ASSERT(refTransaction);
400 m_abortingTransactions.set(transaction.info().identifier(), WTFMove(refTransaction));
402 if (transaction.isVersionChange()) {
403 ASSERT(transaction.originalDatabaseInfo());
404 m_info = *transaction.originalDatabaseInfo();
405 m_closePending = true;
409 void IDBDatabase::didAbortTransaction(IDBTransaction& transaction)
411 LOG(IndexedDB, "IDBDatabase::didAbortTransaction %s", transaction.info().identifier().loggingString().utf8().data());
413 ASSERT(currentThread() == originThreadID());
415 if (transaction.isVersionChange()) {
416 ASSERT(transaction.originalDatabaseInfo());
417 ASSERT(m_info.version() == transaction.originalDatabaseInfo()->version());
418 m_closePending = true;
419 maybeCloseInServer();
422 didCommitOrAbortTransaction(transaction);
425 void IDBDatabase::didCommitOrAbortTransaction(IDBTransaction& transaction)
427 LOG(IndexedDB, "IDBDatabase::didCommitOrAbortTransaction %s", transaction.info().identifier().loggingString().utf8().data());
429 ASSERT(currentThread() == originThreadID());
431 if (m_versionChangeTransaction == &transaction)
432 m_versionChangeTransaction = nullptr;
436 if (m_activeTransactions.contains(transaction.info().identifier()))
438 if (m_committingTransactions.contains(transaction.info().identifier()))
440 if (m_abortingTransactions.contains(transaction.info().identifier()))
446 m_activeTransactions.remove(transaction.info().identifier());
447 m_committingTransactions.remove(transaction.info().identifier());
448 m_abortingTransactions.remove(transaction.info().identifier());
451 maybeCloseInServer();
454 void IDBDatabase::fireVersionChangeEvent(const IDBResourceIdentifier& requestIdentifier, uint64_t requestedVersion)
456 uint64_t currentVersion = m_info.version();
457 LOG(IndexedDB, "IDBDatabase::fireVersionChangeEvent - current version %" PRIu64 ", requested version %" PRIu64 ", connection %" PRIu64 " (%p)", currentVersion, requestedVersion, m_databaseConnectionIdentifier, this);
459 ASSERT(currentThread() == originThreadID());
461 if (!scriptExecutionContext() || m_closePending) {
462 connectionProxy().didFireVersionChangeEvent(m_databaseConnectionIdentifier, requestIdentifier);
466 Ref<Event> event = IDBVersionChangeEvent::create(requestIdentifier, currentVersion, requestedVersion, m_eventNames.versionchangeEvent);
467 event->setTarget(this);
468 scriptExecutionContext()->eventQueue().enqueueEvent(WTFMove(event));
471 bool IDBDatabase::dispatchEvent(Event& event)
473 LOG(IndexedDB, "IDBDatabase::dispatchEvent (%" PRIu64 ") (%p)", m_databaseConnectionIdentifier, this);
474 ASSERT(currentThread() == originThreadID());
476 bool result = EventTargetWithInlineData::dispatchEvent(event);
478 if (event.isVersionChangeEvent() && event.type() == m_eventNames.versionchangeEvent)
479 connectionProxy().didFireVersionChangeEvent(m_databaseConnectionIdentifier, downcast<IDBVersionChangeEvent>(event).requestIdentifier());
484 void IDBDatabase::didCreateIndexInfo(const IDBIndexInfo& info)
486 ASSERT(currentThread() == originThreadID());
488 auto* objectStore = m_info.infoForExistingObjectStore(info.objectStoreIdentifier());
490 objectStore->addExistingIndex(info);
493 void IDBDatabase::didDeleteIndexInfo(const IDBIndexInfo& info)
495 ASSERT(currentThread() == originThreadID());
497 auto* objectStore = m_info.infoForExistingObjectStore(info.objectStoreIdentifier());
499 objectStore->deleteIndex(info.name());
502 } // namespace WebCore
504 #endif // ENABLE(INDEXED_DATABASE)