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"
37 #include "IDBObjectStore.h"
38 #include "IDBOpenDBRequest.h"
39 #include "IDBResultData.h"
40 #include "IDBTransaction.h"
41 #include "IDBVersionChangeEvent.h"
43 #include "ScriptExecutionContext.h"
44 #include <JavaScriptCore/HeapInlines.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(&originThread() == &Thread::current());
69 if (!m_closedInServer)
70 m_connectionProxy->databaseConnectionClosed(*this);
72 m_connectionProxy->unregisterDatabaseConnection(*this);
75 bool IDBDatabase::hasPendingActivity() const
77 ASSERT(&originThread() == &Thread::current() || mayBeGCThread());
79 if (m_closedInServer || isContextStopped())
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(&originThread() == &Thread::current());
94 uint64_t IDBDatabase::version() const
96 ASSERT(&originThread() == &Thread::current());
97 return m_info.version();
100 Ref<DOMStringList> IDBDatabase::objectStoreNames() const
102 ASSERT(&originThread() == &Thread::current());
104 auto 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(&originThread() == &Thread::current());
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(&originThread() == &Thread::current());
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(&originThread() == &Thread::current());
139 ASSERT(!m_versionChangeTransaction || m_versionChangeTransaction->isVersionChange());
141 if (!m_versionChangeTransaction)
142 return Exception { InvalidStateError, "Failed to execute 'createObjectStore' on 'IDBDatabase': The database is not running a version change transaction."_s };
144 if (!m_versionChangeTransaction->isActive())
145 return Exception { TransactionInactiveError };
147 if (m_info.hasObjectStore(name))
148 return Exception { ConstraintError, "Failed to execute 'createObjectStore' on 'IDBDatabase': An object store with the specified name already exists."_s };
150 auto& keyPath = parameters.keyPath;
151 if (keyPath && !isIDBKeyPathValid(keyPath.value()))
152 return Exception { SyntaxError, "Failed to execute 'createObjectStore' on 'IDBDatabase': The keyPath option is not a valid key path."_s };
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 { InvalidAccessError, "Failed to execute 'createObjectStore' on 'IDBDatabase': The autoIncrement option was set but the keyPath option was empty or an array."_s };
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(&originThread() == &Thread::current());
171 return Exception { InvalidStateError, "Failed to execute 'transaction' on 'IDBDatabase': The database connection is closing."_s };
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 { InvalidAccessError, "Failed to execute 'transaction' on 'IDBDatabase': The storeNames parameter was empty."_s };
182 if (mode != IDBTransactionMode::Readonly && mode != IDBTransactionMode::Readwrite)
183 return Exception { TypeError };
185 if (m_versionChangeTransaction && !m_versionChangeTransaction->isFinishedOrFinishing())
186 return Exception { InvalidStateError, "Failed to execute 'transaction' on 'IDBDatabase': A version change transaction is running."_s };
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 = copyToVector(objectStoreSet);
196 for (auto& objectStoreName : objectStores) {
197 if (m_info.hasObjectStore(objectStoreName))
199 return Exception { NotFoundError, "Failed to execute 'transaction' on 'IDBDatabase': One of the specified object stores was not found."_s };
202 auto info = IDBTransactionInfo::clientTransaction(m_connectionProxy.get(), objectStores, mode);
204 LOG(IndexedDBOperations, "IDB creating transaction: %s", info.loggingString().utf8().data());
205 auto transaction = IDBTransaction::create(*this, info);
207 LOG(IndexedDB, "IDBDatabase::transaction - Added active transaction %s", info.identifier().loggingString().utf8().data());
209 m_activeTransactions.set(info.identifier(), transaction.ptr());
211 return WTFMove(transaction);
214 ExceptionOr<void> IDBDatabase::deleteObjectStore(const String& objectStoreName)
216 LOG(IndexedDB, "IDBDatabase::deleteObjectStore");
218 ASSERT(&originThread() == &Thread::current());
220 if (!m_versionChangeTransaction)
221 return Exception { InvalidStateError, "Failed to execute 'deleteObjectStore' on 'IDBDatabase': The database is not running a version change transaction."_s };
223 if (!m_versionChangeTransaction->isActive())
224 return Exception { TransactionInactiveError };
226 if (!m_info.hasObjectStore(objectStoreName))
227 return Exception { NotFoundError, "Failed to execute 'deleteObjectStore' on 'IDBDatabase': The specified object store was not found."_s };
229 m_info.deleteObjectStore(objectStoreName);
230 m_versionChangeTransaction->deleteObjectStore(objectStoreName);
235 void IDBDatabase::close()
237 LOG(IndexedDB, "IDBDatabase::close - %" PRIu64, m_databaseConnectionIdentifier);
239 ASSERT(&originThread() == &Thread::current());
241 if (!m_closePending) {
242 m_closePending = true;
243 m_connectionProxy->databaseConnectionPendingClose(*this);
246 maybeCloseInServer();
249 void IDBDatabase::didCloseFromServer(const IDBError& error)
251 LOG(IndexedDB, "IDBDatabase::didCloseFromServer - %" PRIu64, m_databaseConnectionIdentifier);
253 connectionToServerLost(error);
255 m_connectionProxy->confirmDidCloseFromServer(*this);
258 void IDBDatabase::connectionToServerLost(const IDBError& error)
260 LOG(IndexedDB, "IDBDatabase::connectionToServerLost - %" PRIu64, m_databaseConnectionIdentifier);
262 ASSERT(&originThread() == &Thread::current());
264 m_closePending = true;
265 m_closedInServer = true;
267 auto activeTransactions = copyToVector(m_activeTransactions.values());
268 for (auto& transaction : activeTransactions)
269 transaction->connectionClosedFromServer(error);
271 auto committingTransactions = copyToVector(m_committingTransactions.values());
272 for (auto& transaction : committingTransactions)
273 transaction->connectionClosedFromServer(error);
275 auto errorEvent = Event::create(m_eventNames.errorEvent, Event::CanBubble::Yes, Event::IsCancelable::No);
276 errorEvent->setTarget(this);
278 if (auto* context = scriptExecutionContext())
279 context->eventQueue().enqueueEvent(WTFMove(errorEvent));
281 auto closeEvent = Event::create(m_eventNames.closeEvent, Event::CanBubble::Yes, Event::IsCancelable::No);
282 closeEvent->setTarget(this);
284 if (auto* context = scriptExecutionContext())
285 context->eventQueue().enqueueEvent(WTFMove(closeEvent));
288 void IDBDatabase::maybeCloseInServer()
290 LOG(IndexedDB, "IDBDatabase::maybeCloseInServer - %" PRIu64, m_databaseConnectionIdentifier);
292 ASSERT(&originThread() == &Thread::current());
294 if (m_closedInServer)
297 // 3.3.9 Database closing steps
298 // Wait for all transactions created using this connection to complete.
299 // Once they are complete, this connection is closed.
300 if (!m_activeTransactions.isEmpty() || !m_committingTransactions.isEmpty())
303 m_closedInServer = true;
304 m_connectionProxy->databaseConnectionClosed(*this);
307 const char* IDBDatabase::activeDOMObjectName() const
309 ASSERT(&originThread() == &Thread::current());
310 return "IDBDatabase";
313 bool IDBDatabase::canSuspendForDocumentSuspension() const
315 ASSERT(&originThread() == &Thread::current());
317 // FIXME: This value will sometimes be false when database operations are actually in progress.
318 // Such database operations do not yet exist.
322 void IDBDatabase::stop()
324 LOG(IndexedDB, "IDBDatabase::stop - %" PRIu64, m_databaseConnectionIdentifier);
326 ASSERT(&originThread() == &Thread::current());
328 removeAllEventListeners();
330 Vector<IDBResourceIdentifier> transactionIdentifiers;
331 transactionIdentifiers.reserveInitialCapacity(m_activeTransactions.size());
333 for (auto& id : m_activeTransactions.keys())
334 transactionIdentifiers.uncheckedAppend(id);
336 for (auto& id : transactionIdentifiers) {
337 IDBTransaction* transaction = m_activeTransactions.get(id);
345 Ref<IDBTransaction> IDBDatabase::startVersionChangeTransaction(const IDBTransactionInfo& info, IDBOpenDBRequest& request)
347 LOG(IndexedDB, "IDBDatabase::startVersionChangeTransaction %s", info.identifier().loggingString().utf8().data());
349 ASSERT(&originThread() == &Thread::current());
350 ASSERT(!m_versionChangeTransaction);
351 ASSERT(info.mode() == IDBTransactionMode::Versionchange);
352 ASSERT(!m_closePending);
353 ASSERT(scriptExecutionContext());
355 Ref<IDBTransaction> transaction = IDBTransaction::create(*this, info, request);
356 m_versionChangeTransaction = &transaction.get();
358 m_activeTransactions.set(transaction->info().identifier(), &transaction.get());
363 void IDBDatabase::didStartTransaction(IDBTransaction& transaction)
365 LOG(IndexedDB, "IDBDatabase::didStartTransaction %s", transaction.info().identifier().loggingString().utf8().data());
366 ASSERT(!m_versionChangeTransaction);
367 ASSERT(&originThread() == &Thread::current());
369 // It is possible for the client to have aborted a transaction before the server replies back that it has started.
370 if (m_abortingTransactions.contains(transaction.info().identifier()))
373 m_activeTransactions.set(transaction.info().identifier(), &transaction);
376 void IDBDatabase::willCommitTransaction(IDBTransaction& transaction)
378 LOG(IndexedDB, "IDBDatabase::willCommitTransaction %s", transaction.info().identifier().loggingString().utf8().data());
380 ASSERT(&originThread() == &Thread::current());
382 auto refTransaction = m_activeTransactions.take(transaction.info().identifier());
383 ASSERT(refTransaction);
384 m_committingTransactions.set(transaction.info().identifier(), WTFMove(refTransaction));
387 void IDBDatabase::didCommitTransaction(IDBTransaction& transaction)
389 LOG(IndexedDB, "IDBDatabase::didCommitTransaction %s", transaction.info().identifier().loggingString().utf8().data());
391 ASSERT(&originThread() == &Thread::current());
393 if (m_versionChangeTransaction == &transaction)
394 m_info.setVersion(transaction.info().newVersion());
396 didCommitOrAbortTransaction(transaction);
399 void IDBDatabase::willAbortTransaction(IDBTransaction& transaction)
401 LOG(IndexedDB, "IDBDatabase::willAbortTransaction %s", transaction.info().identifier().loggingString().utf8().data());
403 ASSERT(&originThread() == &Thread::current());
405 auto refTransaction = m_activeTransactions.take(transaction.info().identifier());
407 refTransaction = m_committingTransactions.take(transaction.info().identifier());
409 ASSERT(refTransaction);
410 m_abortingTransactions.set(transaction.info().identifier(), WTFMove(refTransaction));
412 if (transaction.isVersionChange()) {
413 ASSERT(transaction.originalDatabaseInfo());
414 m_info = *transaction.originalDatabaseInfo();
415 m_closePending = true;
419 void IDBDatabase::didAbortTransaction(IDBTransaction& transaction)
421 LOG(IndexedDB, "IDBDatabase::didAbortTransaction %s", transaction.info().identifier().loggingString().utf8().data());
423 ASSERT(&originThread() == &Thread::current());
425 if (transaction.isVersionChange()) {
426 ASSERT(transaction.originalDatabaseInfo());
427 ASSERT(m_info.version() == transaction.originalDatabaseInfo()->version());
428 m_closePending = true;
429 maybeCloseInServer();
432 didCommitOrAbortTransaction(transaction);
435 void IDBDatabase::didCommitOrAbortTransaction(IDBTransaction& transaction)
437 LOG(IndexedDB, "IDBDatabase::didCommitOrAbortTransaction %s", transaction.info().identifier().loggingString().utf8().data());
439 ASSERT(&originThread() == &Thread::current());
441 if (m_versionChangeTransaction == &transaction)
442 m_versionChangeTransaction = nullptr;
446 if (m_activeTransactions.contains(transaction.info().identifier()))
448 if (m_committingTransactions.contains(transaction.info().identifier()))
450 if (m_abortingTransactions.contains(transaction.info().identifier()))
456 m_activeTransactions.remove(transaction.info().identifier());
457 m_committingTransactions.remove(transaction.info().identifier());
458 m_abortingTransactions.remove(transaction.info().identifier());
461 maybeCloseInServer();
464 void IDBDatabase::fireVersionChangeEvent(const IDBResourceIdentifier& requestIdentifier, uint64_t requestedVersion)
466 uint64_t currentVersion = m_info.version();
467 LOG(IndexedDB, "IDBDatabase::fireVersionChangeEvent - current version %" PRIu64 ", requested version %" PRIu64 ", connection %" PRIu64 " (%p)", currentVersion, requestedVersion, m_databaseConnectionIdentifier, this);
469 ASSERT(&originThread() == &Thread::current());
471 if (!scriptExecutionContext() || m_closePending) {
472 connectionProxy().didFireVersionChangeEvent(m_databaseConnectionIdentifier, requestIdentifier);
476 Ref<Event> event = IDBVersionChangeEvent::create(requestIdentifier, currentVersion, requestedVersion, m_eventNames.versionchangeEvent);
477 event->setTarget(this);
478 scriptExecutionContext()->eventQueue().enqueueEvent(WTFMove(event));
481 void IDBDatabase::dispatchEvent(Event& event)
483 LOG(IndexedDB, "IDBDatabase::dispatchEvent (%" PRIu64 ") (%p)", m_databaseConnectionIdentifier, this);
484 ASSERT(&originThread() == &Thread::current());
486 auto protectedThis = makeRef(*this);
488 EventTargetWithInlineData::dispatchEvent(event);
490 if (event.isVersionChangeEvent() && event.type() == m_eventNames.versionchangeEvent)
491 m_connectionProxy->didFireVersionChangeEvent(m_databaseConnectionIdentifier, downcast<IDBVersionChangeEvent>(event).requestIdentifier());
494 void IDBDatabase::didCreateIndexInfo(const IDBIndexInfo& info)
496 ASSERT(&originThread() == &Thread::current());
498 auto* objectStore = m_info.infoForExistingObjectStore(info.objectStoreIdentifier());
500 objectStore->addExistingIndex(info);
503 void IDBDatabase::didDeleteIndexInfo(const IDBIndexInfo& info)
505 ASSERT(&originThread() == &Thread::current());
507 auto* objectStore = m_info.infoForExistingObjectStore(info.objectStoreIdentifier());
509 objectStore->deleteIndex(info.name());
512 } // namespace WebCore
514 #endif // ENABLE(INDEXED_DATABASE)