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 if (!m_closePending) {
241 m_closePending = true;
242 m_connectionProxy->databaseConnectionPendingClose(*this);
245 maybeCloseInServer();
248 void IDBDatabase::didCloseFromServer(const IDBError& error)
250 LOG(IndexedDB, "IDBDatabase::didCloseFromServer - %" PRIu64, m_databaseConnectionIdentifier);
252 connectionToServerLost(error);
254 m_connectionProxy->confirmDidCloseFromServer(*this);
257 void IDBDatabase::connectionToServerLost(const IDBError& error)
259 LOG(IndexedDB, "IDBDatabase::connectionToServerLost - %" PRIu64, m_databaseConnectionIdentifier);
261 ASSERT(currentThread() == originThreadID());
263 m_closePending = true;
264 m_closedInServer = true;
266 for (auto& transaction : m_activeTransactions.values())
267 transaction->connectionClosedFromServer(error);
269 auto errorEvent = Event::create(m_eventNames.errorEvent, true, false);
270 errorEvent->setTarget(this);
272 if (auto* context = scriptExecutionContext())
273 context->eventQueue().enqueueEvent(WTFMove(errorEvent));
275 auto closeEvent = Event::create(m_eventNames.closeEvent, true, false);
276 closeEvent->setTarget(this);
278 if (auto* context = scriptExecutionContext())
279 context->eventQueue().enqueueEvent(WTFMove(closeEvent));
282 void IDBDatabase::maybeCloseInServer()
284 LOG(IndexedDB, "IDBDatabase::maybeCloseInServer - %" PRIu64, m_databaseConnectionIdentifier);
286 ASSERT(currentThread() == originThreadID());
288 if (m_closedInServer)
291 // 3.3.9 Database closing steps
292 // Wait for all transactions created using this connection to complete.
293 // Once they are complete, this connection is closed.
294 if (!m_activeTransactions.isEmpty() || !m_committingTransactions.isEmpty())
297 m_closedInServer = true;
298 m_connectionProxy->databaseConnectionClosed(*this);
301 const char* IDBDatabase::activeDOMObjectName() const
303 ASSERT(currentThread() == originThreadID());
304 return "IDBDatabase";
307 bool IDBDatabase::canSuspendForDocumentSuspension() const
309 ASSERT(currentThread() == originThreadID());
311 // FIXME: This value will sometimes be false when database operations are actually in progress.
312 // Such database operations do not yet exist.
316 void IDBDatabase::stop()
318 LOG(IndexedDB, "IDBDatabase::stop - %" PRIu64, m_databaseConnectionIdentifier);
320 ASSERT(currentThread() == originThreadID());
322 removeAllEventListeners();
324 Vector<IDBResourceIdentifier> transactionIdentifiers;
325 transactionIdentifiers.reserveInitialCapacity(m_activeTransactions.size());
327 for (auto& id : m_activeTransactions.keys())
328 transactionIdentifiers.uncheckedAppend(id);
330 for (auto& id : transactionIdentifiers) {
331 IDBTransaction* transaction = m_activeTransactions.get(id);
339 Ref<IDBTransaction> IDBDatabase::startVersionChangeTransaction(const IDBTransactionInfo& info, IDBOpenDBRequest& request)
341 LOG(IndexedDB, "IDBDatabase::startVersionChangeTransaction %s", info.identifier().loggingString().utf8().data());
343 ASSERT(currentThread() == originThreadID());
344 ASSERT(!m_versionChangeTransaction);
345 ASSERT(info.mode() == IDBTransactionMode::Versionchange);
346 ASSERT(!m_closePending);
347 ASSERT(scriptExecutionContext());
349 Ref<IDBTransaction> transaction = IDBTransaction::create(*this, info, request);
350 m_versionChangeTransaction = &transaction.get();
352 m_activeTransactions.set(transaction->info().identifier(), &transaction.get());
357 void IDBDatabase::didStartTransaction(IDBTransaction& transaction)
359 LOG(IndexedDB, "IDBDatabase::didStartTransaction %s", transaction.info().identifier().loggingString().utf8().data());
360 ASSERT(!m_versionChangeTransaction);
361 ASSERT(currentThread() == originThreadID());
363 // It is possible for the client to have aborted a transaction before the server replies back that it has started.
364 if (m_abortingTransactions.contains(transaction.info().identifier()))
367 m_activeTransactions.set(transaction.info().identifier(), &transaction);
370 void IDBDatabase::willCommitTransaction(IDBTransaction& transaction)
372 LOG(IndexedDB, "IDBDatabase::willCommitTransaction %s", transaction.info().identifier().loggingString().utf8().data());
374 ASSERT(currentThread() == originThreadID());
376 auto refTransaction = m_activeTransactions.take(transaction.info().identifier());
377 ASSERT(refTransaction);
378 m_committingTransactions.set(transaction.info().identifier(), WTFMove(refTransaction));
381 void IDBDatabase::didCommitTransaction(IDBTransaction& transaction)
383 LOG(IndexedDB, "IDBDatabase::didCommitTransaction %s", transaction.info().identifier().loggingString().utf8().data());
385 ASSERT(currentThread() == originThreadID());
387 if (m_versionChangeTransaction == &transaction)
388 m_info.setVersion(transaction.info().newVersion());
390 didCommitOrAbortTransaction(transaction);
393 void IDBDatabase::willAbortTransaction(IDBTransaction& transaction)
395 LOG(IndexedDB, "IDBDatabase::willAbortTransaction %s", transaction.info().identifier().loggingString().utf8().data());
397 ASSERT(currentThread() == originThreadID());
399 auto refTransaction = m_activeTransactions.take(transaction.info().identifier());
401 refTransaction = m_committingTransactions.take(transaction.info().identifier());
403 ASSERT(refTransaction);
404 m_abortingTransactions.set(transaction.info().identifier(), WTFMove(refTransaction));
406 if (transaction.isVersionChange()) {
407 ASSERT(transaction.originalDatabaseInfo());
408 m_info = *transaction.originalDatabaseInfo();
409 m_closePending = true;
413 void IDBDatabase::didAbortTransaction(IDBTransaction& transaction)
415 LOG(IndexedDB, "IDBDatabase::didAbortTransaction %s", transaction.info().identifier().loggingString().utf8().data());
417 ASSERT(currentThread() == originThreadID());
419 if (transaction.isVersionChange()) {
420 ASSERT(transaction.originalDatabaseInfo());
421 ASSERT(m_info.version() == transaction.originalDatabaseInfo()->version());
422 m_closePending = true;
423 maybeCloseInServer();
426 didCommitOrAbortTransaction(transaction);
429 void IDBDatabase::didCommitOrAbortTransaction(IDBTransaction& transaction)
431 LOG(IndexedDB, "IDBDatabase::didCommitOrAbortTransaction %s", transaction.info().identifier().loggingString().utf8().data());
433 ASSERT(currentThread() == originThreadID());
435 if (m_versionChangeTransaction == &transaction)
436 m_versionChangeTransaction = nullptr;
440 if (m_activeTransactions.contains(transaction.info().identifier()))
442 if (m_committingTransactions.contains(transaction.info().identifier()))
444 if (m_abortingTransactions.contains(transaction.info().identifier()))
450 m_activeTransactions.remove(transaction.info().identifier());
451 m_committingTransactions.remove(transaction.info().identifier());
452 m_abortingTransactions.remove(transaction.info().identifier());
455 maybeCloseInServer();
458 void IDBDatabase::fireVersionChangeEvent(const IDBResourceIdentifier& requestIdentifier, uint64_t requestedVersion)
460 uint64_t currentVersion = m_info.version();
461 LOG(IndexedDB, "IDBDatabase::fireVersionChangeEvent - current version %" PRIu64 ", requested version %" PRIu64 ", connection %" PRIu64 " (%p)", currentVersion, requestedVersion, m_databaseConnectionIdentifier, this);
463 ASSERT(currentThread() == originThreadID());
465 if (!scriptExecutionContext() || m_closePending) {
466 connectionProxy().didFireVersionChangeEvent(m_databaseConnectionIdentifier, requestIdentifier);
470 Ref<Event> event = IDBVersionChangeEvent::create(requestIdentifier, currentVersion, requestedVersion, m_eventNames.versionchangeEvent);
471 event->setTarget(this);
472 scriptExecutionContext()->eventQueue().enqueueEvent(WTFMove(event));
475 bool IDBDatabase::dispatchEvent(Event& event)
477 LOG(IndexedDB, "IDBDatabase::dispatchEvent (%" PRIu64 ") (%p)", m_databaseConnectionIdentifier, this);
478 ASSERT(currentThread() == originThreadID());
480 bool result = EventTargetWithInlineData::dispatchEvent(event);
482 if (event.isVersionChangeEvent() && event.type() == m_eventNames.versionchangeEvent)
483 connectionProxy().didFireVersionChangeEvent(m_databaseConnectionIdentifier, downcast<IDBVersionChangeEvent>(event).requestIdentifier());
488 void IDBDatabase::didCreateIndexInfo(const IDBIndexInfo& info)
490 ASSERT(currentThread() == originThreadID());
492 auto* objectStore = m_info.infoForExistingObjectStore(info.objectStoreIdentifier());
494 objectStore->addExistingIndex(info);
497 void IDBDatabase::didDeleteIndexInfo(const IDBIndexInfo& info)
499 ASSERT(currentThread() == originThreadID());
501 auto* objectStore = m_info.infoForExistingObjectStore(info.objectStoreIdentifier());
503 objectStore->deleteIndex(info.name());
506 } // namespace WebCore
508 #endif // ENABLE(INDEXED_DATABASE)