Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / modules / webdatabase / SQLTransaction.cpp
1 /*
2  * Copyright (C) 2007, 2008, 2013 Apple 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  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "config.h"
30 #include "modules/webdatabase/SQLTransaction.h"
31
32 #include "bindings/v8/ExceptionState.h"
33 #include "core/dom/ExceptionCode.h"
34 #include "core/html/VoidCallback.h"
35 #include "platform/Logging.h"
36 #include "modules/webdatabase/AbstractSQLTransactionBackend.h"
37 #include "modules/webdatabase/Database.h"
38 #include "modules/webdatabase/DatabaseAuthorizer.h"
39 #include "modules/webdatabase/DatabaseContext.h"
40 #include "modules/webdatabase/SQLError.h"
41 #include "modules/webdatabase/SQLStatementCallback.h"
42 #include "modules/webdatabase/SQLStatementErrorCallback.h"
43 #include "modules/webdatabase/SQLTransactionCallback.h"
44 #include "modules/webdatabase/SQLTransactionClient.h" // FIXME: Should be used in the backend only.
45 #include "modules/webdatabase/SQLTransactionErrorCallback.h"
46 #include "wtf/StdLibExtras.h"
47 #include "wtf/Vector.h"
48
49 namespace WebCore {
50
51 PassRefPtrWillBeRawPtr<SQLTransaction> SQLTransaction::create(Database* db, PassOwnPtr<SQLTransactionCallback> callback,
52     PassOwnPtr<VoidCallback> successCallback, PassOwnPtr<SQLTransactionErrorCallback> errorCallback,
53     bool readOnly)
54 {
55     return adoptRefWillBeNoop(new SQLTransaction(db, callback, successCallback, errorCallback, readOnly));
56 }
57
58 SQLTransaction::SQLTransaction(Database* db, PassOwnPtr<SQLTransactionCallback> callback,
59     PassOwnPtr<VoidCallback> successCallback, PassOwnPtr<SQLTransactionErrorCallback> errorCallback,
60     bool readOnly)
61     : m_database(db)
62     , m_callbackWrapper(callback, db->executionContext())
63     , m_successCallbackWrapper(successCallback, db->executionContext())
64     , m_errorCallbackWrapper(errorCallback, db->executionContext())
65     , m_executeSqlAllowed(false)
66     , m_readOnly(readOnly)
67 {
68     ASSERT(m_database);
69     ScriptWrappable::init(this);
70 }
71
72 void SQLTransaction::trace(Visitor* visitor)
73 {
74     visitor->trace(m_database);
75     visitor->trace(m_backend);
76 }
77
78 bool SQLTransaction::hasCallback() const
79 {
80     return m_callbackWrapper.hasCallback();
81 }
82
83 bool SQLTransaction::hasSuccessCallback() const
84 {
85     return m_successCallbackWrapper.hasCallback();
86 }
87
88 bool SQLTransaction::hasErrorCallback() const
89 {
90     return m_errorCallbackWrapper.hasCallback();
91 }
92
93 void SQLTransaction::setBackend(AbstractSQLTransactionBackend* backend)
94 {
95     ASSERT(!m_backend);
96     m_backend = backend;
97 }
98
99 SQLTransaction::StateFunction SQLTransaction::stateFunctionFor(SQLTransactionState state)
100 {
101     static const StateFunction stateFunctions[] = {
102         &SQLTransaction::unreachableState,                // 0. illegal
103         &SQLTransaction::unreachableState,                // 1. idle
104         &SQLTransaction::unreachableState,                // 2. acquireLock
105         &SQLTransaction::unreachableState,                // 3. openTransactionAndPreflight
106         &SQLTransaction::sendToBackendState,              // 4. runStatements
107         &SQLTransaction::unreachableState,                // 5. postflightAndCommit
108         &SQLTransaction::sendToBackendState,              // 6. cleanupAndTerminate
109         &SQLTransaction::sendToBackendState,              // 7. cleanupAfterTransactionErrorCallback
110         &SQLTransaction::deliverTransactionCallback,      // 8.
111         &SQLTransaction::deliverTransactionErrorCallback, // 9.
112         &SQLTransaction::deliverStatementCallback,        // 10.
113         &SQLTransaction::deliverQuotaIncreaseCallback,    // 11.
114         &SQLTransaction::deliverSuccessCallback           // 12.
115     };
116
117     ASSERT(WTF_ARRAY_LENGTH(stateFunctions) == static_cast<int>(SQLTransactionState::NumberOfStates));
118     ASSERT(state < SQLTransactionState::NumberOfStates);
119
120     return stateFunctions[static_cast<int>(state)];
121 }
122
123 // requestTransitToState() can be called from the backend. Hence, it should
124 // NOT be modifying SQLTransactionBackend in general. The only safe field to
125 // modify is m_requestedState which is meant for this purpose.
126 void SQLTransaction::requestTransitToState(SQLTransactionState nextState)
127 {
128     WTF_LOG(StorageAPI, "Scheduling %s for transaction %p\n", nameForSQLTransactionState(nextState), this);
129     m_requestedState = nextState;
130     m_database->scheduleTransactionCallback(this);
131 }
132
133 SQLTransactionState SQLTransaction::nextStateForTransactionError()
134 {
135     ASSERT(m_transactionError);
136     if (m_errorCallbackWrapper.hasCallback())
137         return SQLTransactionState::DeliverTransactionErrorCallback;
138
139     // No error callback, so fast-forward to:
140     // Transaction Step 11 - Rollback the transaction.
141     return SQLTransactionState::CleanupAfterTransactionErrorCallback;
142 }
143
144 SQLTransactionState SQLTransaction::deliverTransactionCallback()
145 {
146     bool shouldDeliverErrorCallback = false;
147
148     // Spec 4.3.2 4: Invoke the transaction callback with the new SQLTransaction object
149     OwnPtr<SQLTransactionCallback> callback = m_callbackWrapper.unwrap();
150     if (callback) {
151         m_executeSqlAllowed = true;
152         shouldDeliverErrorCallback = !callback->handleEvent(this);
153         m_executeSqlAllowed = false;
154     }
155
156     // Spec 4.3.2 5: If the transaction callback was null or raised an exception, jump to the error callback
157     SQLTransactionState nextState = SQLTransactionState::RunStatements;
158     if (shouldDeliverErrorCallback) {
159         m_database->reportStartTransactionResult(5, SQLError::UNKNOWN_ERR, 0);
160         m_transactionError = SQLErrorData::create(SQLError::UNKNOWN_ERR, "the SQLTransactionCallback was null or threw an exception");
161         nextState = SQLTransactionState::DeliverTransactionErrorCallback;
162     }
163     m_database->reportStartTransactionResult(0, -1, 0); // OK
164     return nextState;
165 }
166
167 SQLTransactionState SQLTransaction::deliverTransactionErrorCallback()
168 {
169     // Spec 4.3.2.10: If exists, invoke error callback with the last
170     // error to have occurred in this transaction.
171     OwnPtr<SQLTransactionErrorCallback> errorCallback = m_errorCallbackWrapper.unwrap();
172     if (errorCallback) {
173         // If we get here with an empty m_transactionError, then the backend
174         // must be waiting in the idle state waiting for this state to finish.
175         // Hence, it's thread safe to fetch the backend transactionError without
176         // a lock.
177         if (!m_transactionError) {
178             ASSERT(m_backend->transactionError());
179             m_transactionError = SQLErrorData::create(*m_backend->transactionError());
180         }
181         ASSERT(m_transactionError);
182         RefPtrWillBeRawPtr<SQLError> error = SQLError::create(*m_transactionError);
183         errorCallback->handleEvent(error.get());
184
185         m_transactionError = nullptr;
186     }
187
188     clearCallbackWrappers();
189
190     // Spec 4.3.2.10: Rollback the transaction.
191     return SQLTransactionState::CleanupAfterTransactionErrorCallback;
192 }
193
194 SQLTransactionState SQLTransaction::deliverStatementCallback()
195 {
196     // Spec 4.3.2.6.6 and 4.3.2.6.3: If the statement callback went wrong, jump to the transaction error callback
197     // Otherwise, continue to loop through the statement queue
198     m_executeSqlAllowed = true;
199
200     AbstractSQLStatement* currentAbstractStatement = m_backend->currentStatement();
201     SQLStatement* currentStatement = static_cast<SQLStatement*>(currentAbstractStatement);
202     ASSERT(currentStatement);
203
204     bool result = currentStatement->performCallback(this);
205
206     m_executeSqlAllowed = false;
207
208     if (result) {
209         m_database->reportCommitTransactionResult(2, SQLError::UNKNOWN_ERR, 0);
210         m_transactionError = SQLErrorData::create(SQLError::UNKNOWN_ERR, "the statement callback raised an exception or statement error callback did not return false");
211         return nextStateForTransactionError();
212     }
213     return SQLTransactionState::RunStatements;
214 }
215
216 SQLTransactionState SQLTransaction::deliverQuotaIncreaseCallback()
217 {
218     ASSERT(m_backend->currentStatement());
219
220     bool shouldRetryCurrentStatement = m_database->transactionClient()->didExceedQuota(database());
221     m_backend->setShouldRetryCurrentStatement(shouldRetryCurrentStatement);
222
223     return SQLTransactionState::RunStatements;
224 }
225
226 SQLTransactionState SQLTransaction::deliverSuccessCallback()
227 {
228     // Spec 4.3.2.8: Deliver success callback.
229     OwnPtr<VoidCallback> successCallback = m_successCallbackWrapper.unwrap();
230     if (successCallback)
231         successCallback->handleEvent();
232
233     clearCallbackWrappers();
234
235     // Schedule a "post-success callback" step to return control to the database thread in case there
236     // are further transactions queued up for this Database
237     return SQLTransactionState::CleanupAndTerminate;
238 }
239
240 // This state function is used as a stub function to plug unimplemented states
241 // in the state dispatch table. They are unimplemented because they should
242 // never be reached in the course of correct execution.
243 SQLTransactionState SQLTransaction::unreachableState()
244 {
245     ASSERT_NOT_REACHED();
246     return SQLTransactionState::End;
247 }
248
249 SQLTransactionState SQLTransaction::sendToBackendState()
250 {
251     ASSERT(m_nextState != SQLTransactionState::Idle);
252     m_backend->requestTransitToState(m_nextState);
253     return SQLTransactionState::Idle;
254 }
255
256 void SQLTransaction::performPendingCallback()
257 {
258     computeNextStateAndCleanupIfNeeded();
259     runStateMachine();
260 }
261
262 void SQLTransaction::executeSQL(const String& sqlStatement, const Vector<SQLValue>& arguments, PassOwnPtr<SQLStatementCallback> callback, PassOwnPtr<SQLStatementErrorCallback> callbackError, ExceptionState& exceptionState)
263 {
264     if (!m_executeSqlAllowed) {
265         exceptionState.throwDOMException(InvalidStateError, "SQL execution is disallowed.");
266         return;
267     }
268
269     if (!m_database->opened()) {
270         exceptionState.throwDOMException(InvalidStateError, "The database has not been opened.");
271         return;
272     }
273
274     int permissions = DatabaseAuthorizer::ReadWriteMask;
275     if (!m_database->databaseContext()->allowDatabaseAccess())
276         permissions |= DatabaseAuthorizer::NoAccessMask;
277     else if (m_readOnly)
278         permissions |= DatabaseAuthorizer::ReadOnlyMask;
279
280     OwnPtr<SQLStatement> statement = SQLStatement::create(m_database.get(), callback, callbackError);
281     m_backend->executeSQL(statement.release(), sqlStatement, arguments, permissions);
282 }
283
284 bool SQLTransaction::computeNextStateAndCleanupIfNeeded()
285 {
286     // Only honor the requested state transition if we're not supposed to be
287     // cleaning up and shutting down:
288     if (m_database->opened() && !m_database->isInterrupted()) {
289         setStateToRequestedState();
290         ASSERT(m_nextState == SQLTransactionState::End
291             || m_nextState == SQLTransactionState::DeliverTransactionCallback
292             || m_nextState == SQLTransactionState::DeliverTransactionErrorCallback
293             || m_nextState == SQLTransactionState::DeliverStatementCallback
294             || m_nextState == SQLTransactionState::DeliverQuotaIncreaseCallback
295             || m_nextState == SQLTransactionState::DeliverSuccessCallback);
296
297         WTF_LOG(StorageAPI, "Callback %s\n", nameForSQLTransactionState(m_nextState));
298         return false;
299     }
300
301     clearCallbackWrappers();
302     m_nextState = SQLTransactionState::CleanupAndTerminate;
303
304     return true;
305 }
306
307 void SQLTransaction::clearCallbackWrappers()
308 {
309     // Release the unneeded callbacks, to break reference cycles.
310     m_callbackWrapper.clear();
311     m_successCallbackWrapper.clear();
312     m_errorCallbackWrapper.clear();
313 }
314
315 PassOwnPtr<SQLTransactionErrorCallback> SQLTransaction::releaseErrorCallback()
316 {
317     return m_errorCallbackWrapper.unwrap();
318 }
319
320 } // namespace WebCore