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/v8/ExceptionState.h"
30 #include "bindings/v8/ExceptionStatePlaceholder.h"
31 #include "bindings/v8/IDBBindingUtilities.h"
32 #include "core/dom/ExecutionContext.h"
33 #include "core/events/EventQueue.h"
34 #include "core/inspector/ScriptCallStack.h"
35 #include "modules/indexeddb/IDBAny.h"
36 #include "modules/indexeddb/IDBEventDispatcher.h"
37 #include "modules/indexeddb/IDBHistograms.h"
38 #include "modules/indexeddb/IDBIndex.h"
39 #include "modules/indexeddb/IDBKeyPath.h"
40 #include "modules/indexeddb/IDBTracing.h"
41 #include "modules/indexeddb/IDBVersionChangeEvent.h"
42 #include "modules/indexeddb/WebIDBDatabaseCallbacksImpl.h"
43 #include "public/platform/Platform.h"
44 #include "public/platform/WebIDBKeyPath.h"
45 #include "wtf/Atomics.h"
48 using blink::WebIDBDatabase;
52 const char IDBDatabase::indexDeletedErrorMessage[] = "The index or its object store has been deleted.";
53 const char IDBDatabase::isKeyCursorErrorMessage[] = "The cursor is a key cursor.";
54 const char IDBDatabase::noKeyOrKeyRangeErrorMessage[] = "No key or key range specified.";
55 const char IDBDatabase::noSuchIndexErrorMessage[] = "The specified index was not found.";
56 const char IDBDatabase::noSuchObjectStoreErrorMessage[] = "The specified object store was not found.";
57 const char IDBDatabase::noValueErrorMessage[] = "The cursor is being iterated or has iterated past its end.";
58 const char IDBDatabase::notValidKeyErrorMessage[] = "The parameter is not a valid key.";
59 const char IDBDatabase::notVersionChangeTransactionErrorMessage[] = "The database is not running a version change transaction.";
60 const char IDBDatabase::objectStoreDeletedErrorMessage[] = "The object store has been deleted.";
61 const char IDBDatabase::requestNotFinishedErrorMessage[] = "The request has not finished.";
62 const char IDBDatabase::sourceDeletedErrorMessage[] = "The cursor's source or effective object store has been deleted.";
63 const char IDBDatabase::transactionInactiveErrorMessage[] = "The transaction is not active.";
64 const char IDBDatabase::transactionFinishedErrorMessage[] = "The transaction has finished.";
65 const char IDBDatabase::transactionReadOnlyErrorMessage[] = "The transaction is read-only.";
67 PassRefPtr<IDBDatabase> IDBDatabase::create(ExecutionContext* context, PassOwnPtr<WebIDBDatabase> database, PassRefPtr<IDBDatabaseCallbacks> callbacks)
69 RefPtr<IDBDatabase> idbDatabase(adoptRef(new IDBDatabase(context, database, callbacks)));
70 idbDatabase->suspendIfNeeded();
71 return idbDatabase.release();
74 IDBDatabase::IDBDatabase(ExecutionContext* context, PassOwnPtr<WebIDBDatabase> backend, PassRefPtr<IDBDatabaseCallbacks> callbacks)
75 : ActiveDOMObject(context)
77 , m_closePending(false)
78 , m_contextStopped(false)
79 , m_databaseCallbacks(callbacks)
81 // We pass a reference of this object before it can be adopted.
82 relaxAdoptionRequirement();
83 ScriptWrappable::init(this);
84 m_databaseCallbacks->connect(this);
87 IDBDatabase::~IDBDatabase()
92 int64_t IDBDatabase::nextTransactionId()
94 // Only keep a 32-bit counter to allow ports to use the other 32
96 AtomicallyInitializedStatic(int, currentTransactionId = 0);
97 return atomicIncrement(¤tTransactionId);
100 void IDBDatabase::indexCreated(int64_t objectStoreId, const IDBIndexMetadata& metadata)
102 IDBDatabaseMetadata::ObjectStoreMap::iterator it = m_metadata.objectStores.find(objectStoreId);
103 ASSERT_WITH_SECURITY_IMPLICATION(it != m_metadata.objectStores.end());
104 it->value.indexes.set(metadata.id, metadata);
107 void IDBDatabase::indexDeleted(int64_t objectStoreId, int64_t indexId)
109 IDBDatabaseMetadata::ObjectStoreMap::iterator it = m_metadata.objectStores.find(objectStoreId);
110 ASSERT_WITH_SECURITY_IMPLICATION(it != m_metadata.objectStores.end());
111 it->value.indexes.remove(indexId);
114 void IDBDatabase::transactionCreated(IDBTransaction* transaction)
117 ASSERT(!m_transactions.contains(transaction->id()));
118 m_transactions.add(transaction->id(), transaction);
120 if (transaction->isVersionChange()) {
121 ASSERT(!m_versionChangeTransaction);
122 m_versionChangeTransaction = transaction;
126 void IDBDatabase::transactionFinished(const IDBTransaction* transaction)
129 ASSERT(m_transactions.contains(transaction->id()));
130 ASSERT(m_transactions.get(transaction->id()) == transaction);
131 m_transactions.remove(transaction->id());
133 if (transaction->isVersionChange()) {
134 ASSERT(m_versionChangeTransaction == transaction);
135 m_versionChangeTransaction = 0;
138 if (m_closePending && m_transactions.isEmpty())
142 void IDBDatabase::onAbort(int64_t transactionId, PassRefPtr<DOMError> error)
144 ASSERT(m_transactions.contains(transactionId));
145 m_transactions.get(transactionId)->onAbort(error);
148 void IDBDatabase::onComplete(int64_t transactionId)
150 ASSERT(m_transactions.contains(transactionId));
151 m_transactions.get(transactionId)->onComplete();
154 PassRefPtr<DOMStringList> IDBDatabase::objectStoreNames() const
156 RefPtr<DOMStringList> objectStoreNames = DOMStringList::create();
157 for (IDBDatabaseMetadata::ObjectStoreMap::const_iterator it = m_metadata.objectStores.begin(); it != m_metadata.objectStores.end(); ++it)
158 objectStoreNames->append(it->value.name);
159 objectStoreNames->sort();
160 return objectStoreNames.release();
163 ScriptValue IDBDatabase::version(ExecutionContext* context) const
165 DOMRequestState requestState(context);
166 int64_t intVersion = m_metadata.intVersion;
167 if (intVersion == IDBDatabaseMetadata::NoIntVersion)
168 return idbAnyToScriptValue(&requestState, IDBAny::createString(m_metadata.version));
170 return idbAnyToScriptValue(&requestState, IDBAny::create(intVersion));
173 PassRefPtr<IDBObjectStore> IDBDatabase::createObjectStore(const String& name, const Dictionary& options, ExceptionState& exceptionState)
176 bool autoIncrement = false;
177 if (!options.isUndefinedOrNull()) {
178 String keyPathString;
179 Vector<String> keyPathArray;
180 if (options.get("keyPath", keyPathArray))
181 keyPath = IDBKeyPath(keyPathArray);
182 else if (options.getWithUndefinedOrNullCheck("keyPath", keyPathString))
183 keyPath = IDBKeyPath(keyPathString);
185 options.get("autoIncrement", autoIncrement);
188 return createObjectStore(name, keyPath, autoIncrement, exceptionState);
191 PassRefPtr<IDBObjectStore> IDBDatabase::createObjectStore(const String& name, const IDBKeyPath& keyPath, bool autoIncrement, ExceptionState& exceptionState)
193 IDB_TRACE("IDBDatabase::createObjectStore");
194 blink::Platform::current()->histogramEnumeration("WebCore.IndexedDB.FrontEndAPICalls", IDBCreateObjectStoreCall, IDBMethodsMax);
195 if (!m_versionChangeTransaction) {
196 exceptionState.throwDOMException(InvalidStateError, IDBDatabase::notVersionChangeTransactionErrorMessage);
199 if (m_versionChangeTransaction->isFinished()) {
200 exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionFinishedErrorMessage);
203 if (!m_versionChangeTransaction->isActive()) {
204 exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionInactiveErrorMessage);
208 if (containsObjectStore(name)) {
209 exceptionState.throwDOMException(ConstraintError, "An object store with the specified name already exists.");
213 if (!keyPath.isNull() && !keyPath.isValid()) {
214 exceptionState.throwDOMException(SyntaxError, "The keyPath option is not a valid key path.");
218 if (autoIncrement && ((keyPath.type() == IDBKeyPath::StringType && keyPath.string().isEmpty()) || keyPath.type() == IDBKeyPath::ArrayType)) {
219 exceptionState.throwDOMException(InvalidAccessError, "The autoIncrement option was set but the keyPath option was empty or an array.");
223 int64_t objectStoreId = m_metadata.maxObjectStoreId + 1;
224 m_backend->createObjectStore(m_versionChangeTransaction->id(), objectStoreId, name, keyPath, autoIncrement);
226 IDBObjectStoreMetadata metadata(name, objectStoreId, keyPath, autoIncrement, WebIDBDatabase::minimumIndexId);
227 RefPtr<IDBObjectStore> objectStore = IDBObjectStore::create(metadata, m_versionChangeTransaction.get());
228 m_metadata.objectStores.set(metadata.id, metadata);
229 ++m_metadata.maxObjectStoreId;
231 m_versionChangeTransaction->objectStoreCreated(name, objectStore);
232 return objectStore.release();
235 void IDBDatabase::deleteObjectStore(const String& name, ExceptionState& exceptionState)
237 IDB_TRACE("IDBDatabase::deleteObjectStore");
238 blink::Platform::current()->histogramEnumeration("WebCore.IndexedDB.FrontEndAPICalls", IDBDeleteObjectStoreCall, IDBMethodsMax);
239 if (!m_versionChangeTransaction) {
240 exceptionState.throwDOMException(InvalidStateError, IDBDatabase::notVersionChangeTransactionErrorMessage);
243 if (m_versionChangeTransaction->isFinished()) {
244 exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionFinishedErrorMessage);
247 if (!m_versionChangeTransaction->isActive()) {
248 exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionInactiveErrorMessage);
252 int64_t objectStoreId = findObjectStoreId(name);
253 if (objectStoreId == IDBObjectStoreMetadata::InvalidId) {
254 exceptionState.throwDOMException(NotFoundError, "The specified object store was not found.");
258 m_backend->deleteObjectStore(m_versionChangeTransaction->id(), objectStoreId);
259 m_versionChangeTransaction->objectStoreDeleted(name);
260 m_metadata.objectStores.remove(objectStoreId);
263 PassRefPtr<IDBTransaction> IDBDatabase::transaction(ExecutionContext* context, const Vector<String>& scope, const String& modeString, ExceptionState& exceptionState)
265 IDB_TRACE("IDBDatabase::transaction");
266 blink::Platform::current()->histogramEnumeration("WebCore.IndexedDB.FrontEndAPICalls", IDBTransactionCall, IDBMethodsMax);
268 exceptionState.throwDOMException(InvalidAccessError, "The storeNames parameter was empty.");
272 blink::WebIDBDatabase::TransactionMode mode = IDBTransaction::stringToMode(modeString, exceptionState);
273 if (exceptionState.hadException())
276 if (m_versionChangeTransaction) {
277 exceptionState.throwDOMException(InvalidStateError, "A version change transaction is running.");
281 if (m_closePending) {
282 exceptionState.throwDOMException(InvalidStateError, "The database connection is closing.");
286 Vector<int64_t> objectStoreIds;
287 for (size_t i = 0; i < scope.size(); ++i) {
288 int64_t objectStoreId = findObjectStoreId(scope[i]);
289 if (objectStoreId == IDBObjectStoreMetadata::InvalidId) {
290 exceptionState.throwDOMException(NotFoundError, "One of the specified object stores was not found.");
293 objectStoreIds.append(objectStoreId);
296 int64_t transactionId = nextTransactionId();
297 m_backend->createTransaction(transactionId, WebIDBDatabaseCallbacksImpl::create(m_databaseCallbacks).leakPtr(), objectStoreIds, mode);
299 RefPtr<IDBTransaction> transaction = IDBTransaction::create(context, transactionId, scope, mode, this);
300 return transaction.release();
303 PassRefPtr<IDBTransaction> IDBDatabase::transaction(ExecutionContext* context, const String& storeName, const String& mode, ExceptionState& exceptionState)
305 RefPtr<DOMStringList> storeNames = DOMStringList::create();
306 storeNames->append(storeName);
307 return transaction(context, storeNames, mode, exceptionState);
310 void IDBDatabase::forceClose()
312 for (TransactionMap::const_iterator::Values it = m_transactions.begin().values(), end = m_transactions.end().values(); it != end; ++it)
313 (*it)->abort(IGNORE_EXCEPTION);
315 enqueueEvent(Event::create(EventTypeNames::close));
318 void IDBDatabase::close()
320 IDB_TRACE("IDBDatabase::close");
324 m_closePending = true;
326 if (m_transactions.isEmpty())
330 void IDBDatabase::closeConnection()
332 ASSERT(m_closePending);
333 ASSERT(m_transactions.isEmpty());
340 if (m_contextStopped || !executionContext())
343 EventQueue* eventQueue = executionContext()->eventQueue();
344 // Remove any pending versionchange events scheduled to fire on this
345 // connection. They would have been scheduled by the backend when another
346 // connection called setVersion, but the frontend connection is being
347 // closed before they could fire.
348 for (size_t i = 0; i < m_enqueuedEvents.size(); ++i) {
349 bool removed = eventQueue->cancelEvent(m_enqueuedEvents[i].get());
350 ASSERT_UNUSED(removed, removed);
354 void IDBDatabase::onVersionChange(int64_t oldVersion, int64_t newVersion)
356 IDB_TRACE("IDBDatabase::onVersionChange");
357 if (m_contextStopped || !executionContext())
363 RefPtr<IDBAny> newVersionAny = newVersion == IDBDatabaseMetadata::NoIntVersion ? IDBAny::createNull() : IDBAny::create(newVersion);
364 enqueueEvent(IDBVersionChangeEvent::create(IDBAny::create(oldVersion), newVersionAny.release(), EventTypeNames::versionchange));
367 void IDBDatabase::enqueueEvent(PassRefPtr<Event> event)
369 ASSERT(!m_contextStopped);
370 ASSERT(executionContext());
371 EventQueue* eventQueue = executionContext()->eventQueue();
372 event->setTarget(this);
373 eventQueue->enqueueEvent(event.get());
374 m_enqueuedEvents.append(event);
377 bool IDBDatabase::dispatchEvent(PassRefPtr<Event> event)
379 IDB_TRACE("IDBDatabase::dispatchEvent");
380 ASSERT(event->type() == EventTypeNames::versionchange || event->type() == EventTypeNames::close);
381 for (size_t i = 0; i < m_enqueuedEvents.size(); ++i) {
382 if (m_enqueuedEvents[i].get() == event.get())
383 m_enqueuedEvents.remove(i);
385 return EventTarget::dispatchEvent(event.get());
388 int64_t IDBDatabase::findObjectStoreId(const String& name) const
390 for (IDBDatabaseMetadata::ObjectStoreMap::const_iterator it = m_metadata.objectStores.begin(); it != m_metadata.objectStores.end(); ++it) {
391 if (it->value.name == name) {
392 ASSERT(it->key != IDBObjectStoreMetadata::InvalidId);
396 return IDBObjectStoreMetadata::InvalidId;
399 bool IDBDatabase::hasPendingActivity() const
401 // The script wrapper must not be collected before the object is closed or
402 // we can't fire a "versionchange" event to let script manually close the connection.
403 return !m_closePending && hasEventListeners() && !m_contextStopped;
406 void IDBDatabase::stop()
408 m_contextStopped = true;
410 // Immediately close the connection to the back end. Don't attempt a
411 // normal close() since that may wait on transactions which require a
412 // round trip to the back-end to abort.
419 const AtomicString& IDBDatabase::interfaceName() const
421 return EventTargetNames::IDBDatabase;
424 ExecutionContext* IDBDatabase::executionContext() const
426 return ActiveDOMObject::executionContext();
429 } // namespace WebCore