2 * Copyright (C) 2010 Google 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
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
18 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
21 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "modules/indexeddb/IDBDatabase.h"
29 #include "bindings/core/v8/ExceptionState.h"
30 #include "bindings/core/v8/ExceptionStatePlaceholder.h"
31 #include "bindings/core/v8/Nullable.h"
32 #include "bindings/core/v8/SerializedScriptValue.h"
33 #include "bindings/modules/v8/IDBBindingUtilities.h"
34 #include "core/dom/ExecutionContext.h"
35 #include "core/events/EventQueue.h"
36 #include "core/inspector/ScriptCallStack.h"
37 #include "modules/indexeddb/IDBAny.h"
38 #include "modules/indexeddb/IDBEventDispatcher.h"
39 #include "modules/indexeddb/IDBHistograms.h"
40 #include "modules/indexeddb/IDBIndex.h"
41 #include "modules/indexeddb/IDBKeyPath.h"
42 #include "modules/indexeddb/IDBTracing.h"
43 #include "modules/indexeddb/IDBVersionChangeEvent.h"
44 #include "modules/indexeddb/WebIDBDatabaseCallbacksImpl.h"
45 #include "public/platform/Platform.h"
46 #include "public/platform/WebIDBKeyPath.h"
47 #include "public/platform/WebIDBTypes.h"
48 #include "wtf/Atomics.h"
51 using blink::WebIDBDatabase;
55 const char IDBDatabase::indexDeletedErrorMessage[] = "The index or its object store has been deleted.";
56 const char IDBDatabase::isKeyCursorErrorMessage[] = "The cursor is a key cursor.";
57 const char IDBDatabase::noKeyOrKeyRangeErrorMessage[] = "No key or key range specified.";
58 const char IDBDatabase::noSuchIndexErrorMessage[] = "The specified index was not found.";
59 const char IDBDatabase::noSuchObjectStoreErrorMessage[] = "The specified object store was not found.";
60 const char IDBDatabase::noValueErrorMessage[] = "The cursor is being iterated or has iterated past its end.";
61 const char IDBDatabase::notValidKeyErrorMessage[] = "The parameter is not a valid key.";
62 const char IDBDatabase::notVersionChangeTransactionErrorMessage[] = "The database is not running a version change transaction.";
63 const char IDBDatabase::objectStoreDeletedErrorMessage[] = "The object store has been deleted.";
64 const char IDBDatabase::requestNotFinishedErrorMessage[] = "The request has not finished.";
65 const char IDBDatabase::sourceDeletedErrorMessage[] = "The cursor's source or effective object store has been deleted.";
66 const char IDBDatabase::transactionInactiveErrorMessage[] = "The transaction is not active.";
67 const char IDBDatabase::transactionFinishedErrorMessage[] = "The transaction has finished.";
68 const char IDBDatabase::transactionReadOnlyErrorMessage[] = "The transaction is read-only.";
69 const char IDBDatabase::databaseClosedErrorMessage[] = "The database connection is closed.";
71 IDBDatabase* IDBDatabase::create(ExecutionContext* context, PassOwnPtr<WebIDBDatabase> database, IDBDatabaseCallbacks* callbacks)
73 IDBDatabase* idbDatabase = adoptRefCountedGarbageCollectedWillBeNoop(new IDBDatabase(context, database, callbacks));
74 idbDatabase->suspendIfNeeded();
78 IDBDatabase::IDBDatabase(ExecutionContext* context, PassOwnPtr<WebIDBDatabase> backend, IDBDatabaseCallbacks* callbacks)
79 : ActiveDOMObject(context)
81 , m_closePending(false)
82 , m_contextStopped(false)
83 , m_databaseCallbacks(callbacks)
85 ScriptWrappable::init(this);
86 m_databaseCallbacks->connect(this);
89 IDBDatabase::~IDBDatabase()
91 if (!m_closePending && m_backend)
95 void IDBDatabase::trace(Visitor* visitor)
97 visitor->trace(m_versionChangeTransaction);
98 visitor->trace(m_transactions);
100 visitor->trace(m_enqueuedEvents);
102 visitor->trace(m_databaseCallbacks);
103 EventTargetWithInlineData::trace(visitor);
106 int64_t IDBDatabase::nextTransactionId()
108 // Only keep a 32-bit counter to allow ports to use the other 32
110 AtomicallyInitializedStatic(int, currentTransactionId = 0);
111 return atomicIncrement(¤tTransactionId);
114 void IDBDatabase::ackReceivedBlobs(const Vector<WebBlobInfo>* blobInfo)
117 if (!blobInfo->size() || !m_backend)
119 Vector<WebBlobInfo>::const_iterator iter;
120 Vector<String> uuids;
121 uuids.reserveCapacity(blobInfo->size());
122 for (iter = blobInfo->begin(); iter != blobInfo->end(); ++iter)
123 uuids.append(iter->uuid());
124 m_backend->ackReceivedBlobs(uuids);
127 void IDBDatabase::indexCreated(int64_t objectStoreId, const IDBIndexMetadata& metadata)
129 IDBDatabaseMetadata::ObjectStoreMap::iterator it = m_metadata.objectStores.find(objectStoreId);
130 ASSERT_WITH_SECURITY_IMPLICATION(it != m_metadata.objectStores.end());
131 it->value.indexes.set(metadata.id, metadata);
134 void IDBDatabase::indexDeleted(int64_t objectStoreId, int64_t indexId)
136 IDBDatabaseMetadata::ObjectStoreMap::iterator it = m_metadata.objectStores.find(objectStoreId);
137 ASSERT_WITH_SECURITY_IMPLICATION(it != m_metadata.objectStores.end());
138 it->value.indexes.remove(indexId);
141 void IDBDatabase::transactionCreated(IDBTransaction* transaction)
144 ASSERT(!m_transactions.contains(transaction->id()));
145 m_transactions.add(transaction->id(), transaction);
147 if (transaction->isVersionChange()) {
148 ASSERT(!m_versionChangeTransaction);
149 m_versionChangeTransaction = transaction;
153 void IDBDatabase::transactionFinished(const IDBTransaction* transaction)
156 ASSERT(m_transactions.contains(transaction->id()));
157 ASSERT(m_transactions.get(transaction->id()) == transaction);
158 m_transactions.remove(transaction->id());
160 if (transaction->isVersionChange()) {
161 ASSERT(m_versionChangeTransaction == transaction);
162 m_versionChangeTransaction = nullptr;
165 if (m_closePending && m_transactions.isEmpty())
169 void IDBDatabase::onAbort(int64_t transactionId, PassRefPtrWillBeRawPtr<DOMError> error)
171 ASSERT(m_transactions.contains(transactionId));
172 m_transactions.get(transactionId)->onAbort(error);
175 void IDBDatabase::onComplete(int64_t transactionId)
177 ASSERT(m_transactions.contains(transactionId));
178 m_transactions.get(transactionId)->onComplete();
181 PassRefPtrWillBeRawPtr<DOMStringList> IDBDatabase::objectStoreNames() const
183 RefPtrWillBeRawPtr<DOMStringList> objectStoreNames = DOMStringList::create();
184 for (IDBDatabaseMetadata::ObjectStoreMap::const_iterator it = m_metadata.objectStores.begin(); it != m_metadata.objectStores.end(); ++it)
185 objectStoreNames->append(it->value.name);
186 objectStoreNames->sort();
187 return objectStoreNames.release();
190 ScriptValue IDBDatabase::version(ScriptState* scriptState) const
192 int64_t intVersion = m_metadata.intVersion;
193 if (intVersion == IDBDatabaseMetadata::NoIntVersion)
194 return idbAnyToScriptValue(scriptState, IDBAny::createString(m_metadata.version));
196 return idbAnyToScriptValue(scriptState, IDBAny::create(intVersion));
199 IDBObjectStore* IDBDatabase::createObjectStore(const String& name, const Dictionary& options, ExceptionState& exceptionState)
202 bool autoIncrement = false;
203 if (!options.isUndefinedOrNull()) {
204 String keyPathString;
205 Vector<String> keyPathArray;
206 if (DictionaryHelper::get(options, "keyPath", keyPathArray))
207 keyPath = IDBKeyPath(keyPathArray);
208 else if (options.getWithUndefinedOrNullCheck("keyPath", keyPathString))
209 keyPath = IDBKeyPath(keyPathString);
211 DictionaryHelper::get(options, "autoIncrement", autoIncrement);
214 return createObjectStore(name, keyPath, autoIncrement, exceptionState);
217 IDBObjectStore* IDBDatabase::createObjectStore(const String& name, const IDBKeyPath& keyPath, bool autoIncrement, ExceptionState& exceptionState)
219 IDB_TRACE("IDBDatabase::createObjectStore");
220 Platform::current()->histogramEnumeration("WebCore.IndexedDB.FrontEndAPICalls", IDBCreateObjectStoreCall, IDBMethodsMax);
221 if (!m_versionChangeTransaction) {
222 exceptionState.throwDOMException(InvalidStateError, IDBDatabase::notVersionChangeTransactionErrorMessage);
225 if (m_versionChangeTransaction->isFinished() || m_versionChangeTransaction->isFinishing()) {
226 exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionFinishedErrorMessage);
229 if (!m_versionChangeTransaction->isActive()) {
230 exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionInactiveErrorMessage);
234 if (containsObjectStore(name)) {
235 exceptionState.throwDOMException(ConstraintError, "An object store with the specified name already exists.");
239 if (!keyPath.isNull() && !keyPath.isValid()) {
240 exceptionState.throwDOMException(SyntaxError, "The keyPath option is not a valid key path.");
244 if (autoIncrement && ((keyPath.type() == IDBKeyPath::StringType && keyPath.string().isEmpty()) || keyPath.type() == IDBKeyPath::ArrayType)) {
245 exceptionState.throwDOMException(InvalidAccessError, "The autoIncrement option was set but the keyPath option was empty or an array.");
250 exceptionState.throwDOMException(InvalidStateError, IDBDatabase::databaseClosedErrorMessage);
254 int64_t objectStoreId = m_metadata.maxObjectStoreId + 1;
255 m_backend->createObjectStore(m_versionChangeTransaction->id(), objectStoreId, name, keyPath, autoIncrement);
257 IDBObjectStoreMetadata metadata(name, objectStoreId, keyPath, autoIncrement, WebIDBDatabase::minimumIndexId);
258 IDBObjectStore* objectStore = IDBObjectStore::create(metadata, m_versionChangeTransaction.get());
259 m_metadata.objectStores.set(metadata.id, metadata);
260 ++m_metadata.maxObjectStoreId;
262 m_versionChangeTransaction->objectStoreCreated(name, objectStore);
266 void IDBDatabase::deleteObjectStore(const String& name, ExceptionState& exceptionState)
268 IDB_TRACE("IDBDatabase::deleteObjectStore");
269 Platform::current()->histogramEnumeration("WebCore.IndexedDB.FrontEndAPICalls", IDBDeleteObjectStoreCall, IDBMethodsMax);
270 if (!m_versionChangeTransaction) {
271 exceptionState.throwDOMException(InvalidStateError, IDBDatabase::notVersionChangeTransactionErrorMessage);
274 if (m_versionChangeTransaction->isFinished() || m_versionChangeTransaction->isFinishing()) {
275 exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionFinishedErrorMessage);
278 if (!m_versionChangeTransaction->isActive()) {
279 exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionInactiveErrorMessage);
283 int64_t objectStoreId = findObjectStoreId(name);
284 if (objectStoreId == IDBObjectStoreMetadata::InvalidId) {
285 exceptionState.throwDOMException(NotFoundError, "The specified object store was not found.");
290 exceptionState.throwDOMException(InvalidStateError, IDBDatabase::databaseClosedErrorMessage);
294 m_backend->deleteObjectStore(m_versionChangeTransaction->id(), objectStoreId);
295 m_versionChangeTransaction->objectStoreDeleted(name);
296 m_metadata.objectStores.remove(objectStoreId);
299 IDBTransaction* IDBDatabase::transaction(ExecutionContext* context, const Vector<String>& scope, const String& modeString, ExceptionState& exceptionState)
301 IDB_TRACE("IDBDatabase::transaction");
302 Platform::current()->histogramEnumeration("WebCore.IndexedDB.FrontEndAPICalls", IDBTransactionCall, IDBMethodsMax);
304 exceptionState.throwDOMException(InvalidAccessError, "The storeNames parameter was empty.");
308 WebIDBTransactionMode mode = IDBTransaction::stringToMode(modeString, exceptionState);
309 if (exceptionState.hadException())
312 if (m_versionChangeTransaction) {
313 exceptionState.throwDOMException(InvalidStateError, "A version change transaction is running.");
317 if (m_closePending) {
318 exceptionState.throwDOMException(InvalidStateError, "The database connection is closing.");
322 Vector<int64_t> objectStoreIds;
323 for (size_t i = 0; i < scope.size(); ++i) {
324 int64_t objectStoreId = findObjectStoreId(scope[i]);
325 if (objectStoreId == IDBObjectStoreMetadata::InvalidId) {
326 exceptionState.throwDOMException(NotFoundError, "One of the specified object stores was not found.");
329 objectStoreIds.append(objectStoreId);
333 exceptionState.throwDOMException(InvalidStateError, IDBDatabase::databaseClosedErrorMessage);
337 int64_t transactionId = nextTransactionId();
338 m_backend->createTransaction(transactionId, WebIDBDatabaseCallbacksImpl::create(m_databaseCallbacks).leakPtr(), objectStoreIds, mode);
340 return IDBTransaction::create(context, transactionId, scope, mode, this);
343 IDBTransaction* IDBDatabase::transaction(ExecutionContext* context, const String& storeName, const String& mode, ExceptionState& exceptionState)
345 RefPtrWillBeRawPtr<DOMStringList> storeNames = DOMStringList::create();
346 storeNames->append(storeName);
347 return transaction(context, storeNames, mode, exceptionState);
350 void IDBDatabase::forceClose()
352 for (TransactionMap::const_iterator::Values it = m_transactions.begin().values(), end = m_transactions.end().values(); it != end; ++it)
353 (*it)->abort(IGNORE_EXCEPTION);
355 enqueueEvent(Event::create(EventTypeNames::close));
358 void IDBDatabase::close()
360 IDB_TRACE("IDBDatabase::close");
364 m_closePending = true;
366 if (m_transactions.isEmpty())
370 void IDBDatabase::closeConnection()
372 ASSERT(m_closePending);
373 ASSERT(m_transactions.isEmpty());
380 if (m_contextStopped || !executionContext())
383 EventQueue* eventQueue = executionContext()->eventQueue();
384 // Remove any pending versionchange events scheduled to fire on this
385 // connection. They would have been scheduled by the backend when another
386 // connection called setVersion, but the frontend connection is being
387 // closed before they could fire.
388 for (size_t i = 0; i < m_enqueuedEvents.size(); ++i) {
389 bool removed = eventQueue->cancelEvent(m_enqueuedEvents[i].get());
390 ASSERT_UNUSED(removed, removed);
394 void IDBDatabase::onVersionChange(int64_t oldVersion, int64_t newVersion)
396 IDB_TRACE("IDBDatabase::onVersionChange");
397 if (m_contextStopped || !executionContext())
400 if (m_closePending) {
401 // If we're pending, that means there's a busy transaction. We won't
402 // fire 'versionchange' but since we're not closing immediately the
403 // back-end should still send out 'blocked'.
404 m_backend->versionChangeIgnored();
408 Nullable<unsigned long long> newVersionNullable = (newVersion == IDBDatabaseMetadata::NoIntVersion) ? Nullable<unsigned long long>() : Nullable<unsigned long long>(newVersion);
409 enqueueEvent(IDBVersionChangeEvent::create(EventTypeNames::versionchange, oldVersion, newVersionNullable));
412 void IDBDatabase::enqueueEvent(PassRefPtrWillBeRawPtr<Event> event)
414 ASSERT(!m_contextStopped);
415 ASSERT(executionContext());
416 EventQueue* eventQueue = executionContext()->eventQueue();
417 event->setTarget(this);
418 eventQueue->enqueueEvent(event.get());
419 m_enqueuedEvents.append(event);
422 bool IDBDatabase::dispatchEvent(PassRefPtrWillBeRawPtr<Event> event)
424 IDB_TRACE("IDBDatabase::dispatchEvent");
425 if (m_contextStopped || !executionContext())
427 ASSERT(event->type() == EventTypeNames::versionchange || event->type() == EventTypeNames::close);
428 for (size_t i = 0; i < m_enqueuedEvents.size(); ++i) {
429 if (m_enqueuedEvents[i].get() == event.get())
430 m_enqueuedEvents.remove(i);
433 bool result = EventTarget::dispatchEvent(event.get());
434 if (event->type() == EventTypeNames::versionchange && !m_closePending && m_backend)
435 m_backend->versionChangeIgnored();
439 int64_t IDBDatabase::findObjectStoreId(const String& name) const
441 for (IDBDatabaseMetadata::ObjectStoreMap::const_iterator it = m_metadata.objectStores.begin(); it != m_metadata.objectStores.end(); ++it) {
442 if (it->value.name == name) {
443 ASSERT(it->key != IDBObjectStoreMetadata::InvalidId);
447 return IDBObjectStoreMetadata::InvalidId;
450 bool IDBDatabase::hasPendingActivity() const
452 // The script wrapper must not be collected before the object is closed or
453 // we can't fire a "versionchange" event to let script manually close the connection.
454 return !m_closePending && hasEventListeners() && !m_contextStopped;
457 void IDBDatabase::stop()
459 m_contextStopped = true;
461 // Immediately close the connection to the back end. Don't attempt a
462 // normal close() since that may wait on transactions which require a
463 // round trip to the back-end to abort.
470 const AtomicString& IDBDatabase::interfaceName() const
472 return EventTargetNames::IDBDatabase;
475 ExecutionContext* IDBDatabase::executionContext() const
477 return ActiveDOMObject::executionContext();