Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / modules / indexeddb / IDBDatabase.cpp
1 /*
2  * Copyright (C) 2010 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
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.
13  *
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.
24  */
25
26 #include "config.h"
27 #include "modules/indexeddb/IDBDatabase.h"
28
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"
46 #include <limits>
47
48 using blink::WebIDBDatabase;
49
50 namespace WebCore {
51
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.";
66
67 PassRefPtr<IDBDatabase> IDBDatabase::create(ExecutionContext* context, PassOwnPtr<WebIDBDatabase> database, PassRefPtr<IDBDatabaseCallbacks> callbacks)
68 {
69     RefPtr<IDBDatabase> idbDatabase(adoptRef(new IDBDatabase(context, database, callbacks)));
70     idbDatabase->suspendIfNeeded();
71     return idbDatabase.release();
72 }
73
74 IDBDatabase::IDBDatabase(ExecutionContext* context, PassOwnPtr<WebIDBDatabase> backend, PassRefPtr<IDBDatabaseCallbacks> callbacks)
75     : ActiveDOMObject(context)
76     , m_backend(backend)
77     , m_closePending(false)
78     , m_contextStopped(false)
79     , m_databaseCallbacks(callbacks)
80 {
81     // We pass a reference of this object before it can be adopted.
82     relaxAdoptionRequirement();
83     ScriptWrappable::init(this);
84     m_databaseCallbacks->connect(this);
85 }
86
87 IDBDatabase::~IDBDatabase()
88 {
89     close();
90 }
91
92 int64_t IDBDatabase::nextTransactionId()
93 {
94     // Only keep a 32-bit counter to allow ports to use the other 32
95     // bits of the id.
96     AtomicallyInitializedStatic(int, currentTransactionId = 0);
97     return atomicIncrement(&currentTransactionId);
98 }
99
100 void IDBDatabase::indexCreated(int64_t objectStoreId, const IDBIndexMetadata& metadata)
101 {
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);
105 }
106
107 void IDBDatabase::indexDeleted(int64_t objectStoreId, int64_t indexId)
108 {
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);
112 }
113
114 void IDBDatabase::transactionCreated(IDBTransaction* transaction)
115 {
116     ASSERT(transaction);
117     ASSERT(!m_transactions.contains(transaction->id()));
118     m_transactions.add(transaction->id(), transaction);
119
120     if (transaction->isVersionChange()) {
121         ASSERT(!m_versionChangeTransaction);
122         m_versionChangeTransaction = transaction;
123     }
124 }
125
126 void IDBDatabase::transactionFinished(const IDBTransaction* transaction)
127 {
128     ASSERT(transaction);
129     ASSERT(m_transactions.contains(transaction->id()));
130     ASSERT(m_transactions.get(transaction->id()) == transaction);
131     m_transactions.remove(transaction->id());
132
133     if (transaction->isVersionChange()) {
134         ASSERT(m_versionChangeTransaction == transaction);
135         m_versionChangeTransaction = 0;
136     }
137
138     if (m_closePending && m_transactions.isEmpty())
139         closeConnection();
140 }
141
142 void IDBDatabase::onAbort(int64_t transactionId, PassRefPtr<DOMError> error)
143 {
144     ASSERT(m_transactions.contains(transactionId));
145     m_transactions.get(transactionId)->onAbort(error);
146 }
147
148 void IDBDatabase::onComplete(int64_t transactionId)
149 {
150     ASSERT(m_transactions.contains(transactionId));
151     m_transactions.get(transactionId)->onComplete();
152 }
153
154 PassRefPtr<DOMStringList> IDBDatabase::objectStoreNames() const
155 {
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();
161 }
162
163 ScriptValue IDBDatabase::version(ExecutionContext* context) const
164 {
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));
169
170     return idbAnyToScriptValue(&requestState, IDBAny::create(intVersion));
171 }
172
173 PassRefPtr<IDBObjectStore> IDBDatabase::createObjectStore(const String& name, const Dictionary& options, ExceptionState& exceptionState)
174 {
175     IDBKeyPath keyPath;
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);
184
185         options.get("autoIncrement", autoIncrement);
186     }
187
188     return createObjectStore(name, keyPath, autoIncrement, exceptionState);
189 }
190
191 PassRefPtr<IDBObjectStore> IDBDatabase::createObjectStore(const String& name, const IDBKeyPath& keyPath, bool autoIncrement, ExceptionState& exceptionState)
192 {
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);
197         return 0;
198     }
199     if (m_versionChangeTransaction->isFinished()) {
200         exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionFinishedErrorMessage);
201         return 0;
202     }
203     if (!m_versionChangeTransaction->isActive()) {
204         exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionInactiveErrorMessage);
205         return 0;
206     }
207
208     if (containsObjectStore(name)) {
209         exceptionState.throwDOMException(ConstraintError, "An object store with the specified name already exists.");
210         return 0;
211     }
212
213     if (!keyPath.isNull() && !keyPath.isValid()) {
214         exceptionState.throwDOMException(SyntaxError, "The keyPath option is not a valid key path.");
215         return 0;
216     }
217
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.");
220         return 0;
221     }
222
223     int64_t objectStoreId = m_metadata.maxObjectStoreId + 1;
224     m_backend->createObjectStore(m_versionChangeTransaction->id(), objectStoreId, name, keyPath, autoIncrement);
225
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;
230
231     m_versionChangeTransaction->objectStoreCreated(name, objectStore);
232     return objectStore.release();
233 }
234
235 void IDBDatabase::deleteObjectStore(const String& name, ExceptionState& exceptionState)
236 {
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);
241         return;
242     }
243     if (m_versionChangeTransaction->isFinished()) {
244         exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionFinishedErrorMessage);
245         return;
246     }
247     if (!m_versionChangeTransaction->isActive()) {
248         exceptionState.throwDOMException(TransactionInactiveError, IDBDatabase::transactionInactiveErrorMessage);
249         return;
250     }
251
252     int64_t objectStoreId = findObjectStoreId(name);
253     if (objectStoreId == IDBObjectStoreMetadata::InvalidId) {
254         exceptionState.throwDOMException(NotFoundError, "The specified object store was not found.");
255         return;
256     }
257
258     m_backend->deleteObjectStore(m_versionChangeTransaction->id(), objectStoreId);
259     m_versionChangeTransaction->objectStoreDeleted(name);
260     m_metadata.objectStores.remove(objectStoreId);
261 }
262
263 PassRefPtr<IDBTransaction> IDBDatabase::transaction(ExecutionContext* context, const Vector<String>& scope, const String& modeString, ExceptionState& exceptionState)
264 {
265     IDB_TRACE("IDBDatabase::transaction");
266     blink::Platform::current()->histogramEnumeration("WebCore.IndexedDB.FrontEndAPICalls", IDBTransactionCall, IDBMethodsMax);
267     if (!scope.size()) {
268         exceptionState.throwDOMException(InvalidAccessError, "The storeNames parameter was empty.");
269         return 0;
270     }
271
272     blink::WebIDBDatabase::TransactionMode mode = IDBTransaction::stringToMode(modeString, exceptionState);
273     if (exceptionState.hadException())
274         return 0;
275
276     if (m_versionChangeTransaction) {
277         exceptionState.throwDOMException(InvalidStateError, "A version change transaction is running.");
278         return 0;
279     }
280
281     if (m_closePending) {
282         exceptionState.throwDOMException(InvalidStateError, "The database connection is closing.");
283         return 0;
284     }
285
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.");
291             return 0;
292         }
293         objectStoreIds.append(objectStoreId);
294     }
295
296     int64_t transactionId = nextTransactionId();
297     m_backend->createTransaction(transactionId, WebIDBDatabaseCallbacksImpl::create(m_databaseCallbacks).leakPtr(), objectStoreIds, mode);
298
299     RefPtr<IDBTransaction> transaction = IDBTransaction::create(context, transactionId, scope, mode, this);
300     return transaction.release();
301 }
302
303 PassRefPtr<IDBTransaction> IDBDatabase::transaction(ExecutionContext* context, const String& storeName, const String& mode, ExceptionState& exceptionState)
304 {
305     RefPtr<DOMStringList> storeNames = DOMStringList::create();
306     storeNames->append(storeName);
307     return transaction(context, storeNames, mode, exceptionState);
308 }
309
310 void IDBDatabase::forceClose()
311 {
312     for (TransactionMap::const_iterator::Values it = m_transactions.begin().values(), end = m_transactions.end().values(); it != end; ++it)
313         (*it)->abort(IGNORE_EXCEPTION);
314     this->close();
315     enqueueEvent(Event::create(EventTypeNames::close));
316 }
317
318 void IDBDatabase::close()
319 {
320     IDB_TRACE("IDBDatabase::close");
321     if (m_closePending)
322         return;
323
324     m_closePending = true;
325
326     if (m_transactions.isEmpty())
327         closeConnection();
328 }
329
330 void IDBDatabase::closeConnection()
331 {
332     ASSERT(m_closePending);
333     ASSERT(m_transactions.isEmpty());
334
335     if (m_backend) {
336         m_backend->close();
337         m_backend.clear();
338     }
339
340     if (m_contextStopped || !executionContext())
341         return;
342
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);
351     }
352 }
353
354 void IDBDatabase::onVersionChange(int64_t oldVersion, int64_t newVersion)
355 {
356     IDB_TRACE("IDBDatabase::onVersionChange");
357     if (m_contextStopped || !executionContext())
358         return;
359
360     if (m_closePending)
361         return;
362
363     RefPtr<IDBAny> newVersionAny = newVersion == IDBDatabaseMetadata::NoIntVersion ? IDBAny::createNull() : IDBAny::create(newVersion);
364     enqueueEvent(IDBVersionChangeEvent::create(IDBAny::create(oldVersion), newVersionAny.release(), EventTypeNames::versionchange));
365 }
366
367 void IDBDatabase::enqueueEvent(PassRefPtr<Event> event)
368 {
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);
375 }
376
377 bool IDBDatabase::dispatchEvent(PassRefPtr<Event> event)
378 {
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);
384     }
385     return EventTarget::dispatchEvent(event.get());
386 }
387
388 int64_t IDBDatabase::findObjectStoreId(const String& name) const
389 {
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);
393             return it->key;
394         }
395     }
396     return IDBObjectStoreMetadata::InvalidId;
397 }
398
399 bool IDBDatabase::hasPendingActivity() const
400 {
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;
404 }
405
406 void IDBDatabase::stop()
407 {
408     m_contextStopped = true;
409
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.
413     if (m_backend) {
414         m_backend->close();
415         m_backend.clear();
416     }
417 }
418
419 const AtomicString& IDBDatabase::interfaceName() const
420 {
421     return EventTargetNames::IDBDatabase;
422 }
423
424 ExecutionContext* IDBDatabase::executionContext() const
425 {
426     return ActiveDOMObject::executionContext();
427 }
428
429 } // namespace WebCore