2 * Copyright (C) 2007, 2008, 2013 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
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.
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.
30 #include "modules/webdatabase/SQLTransaction.h"
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"
51 PassRefPtrWillBeRawPtr<SQLTransaction> SQLTransaction::create(Database* db, PassOwnPtr<SQLTransactionCallback> callback,
52 PassOwnPtr<VoidCallback> successCallback, PassOwnPtr<SQLTransactionErrorCallback> errorCallback,
55 return adoptRefWillBeNoop(new SQLTransaction(db, callback, successCallback, errorCallback, readOnly));
58 SQLTransaction::SQLTransaction(Database* db, PassOwnPtr<SQLTransactionCallback> callback,
59 PassOwnPtr<VoidCallback> successCallback, PassOwnPtr<SQLTransactionErrorCallback> errorCallback,
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)
69 ScriptWrappable::init(this);
72 void SQLTransaction::trace(Visitor* visitor)
74 visitor->trace(m_database);
75 visitor->trace(m_backend);
78 bool SQLTransaction::hasCallback() const
80 return m_callbackWrapper.hasCallback();
83 bool SQLTransaction::hasSuccessCallback() const
85 return m_successCallbackWrapper.hasCallback();
88 bool SQLTransaction::hasErrorCallback() const
90 return m_errorCallbackWrapper.hasCallback();
93 void SQLTransaction::setBackend(AbstractSQLTransactionBackend* backend)
99 SQLTransaction::StateFunction SQLTransaction::stateFunctionFor(SQLTransactionState state)
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.
117 ASSERT(WTF_ARRAY_LENGTH(stateFunctions) == static_cast<int>(SQLTransactionState::NumberOfStates));
118 ASSERT(state < SQLTransactionState::NumberOfStates);
120 return stateFunctions[static_cast<int>(state)];
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)
128 WTF_LOG(StorageAPI, "Scheduling %s for transaction %p\n", nameForSQLTransactionState(nextState), this);
129 m_requestedState = nextState;
130 m_database->scheduleTransactionCallback(this);
133 SQLTransactionState SQLTransaction::nextStateForTransactionError()
135 ASSERT(m_transactionError);
136 if (m_errorCallbackWrapper.hasCallback())
137 return SQLTransactionState::DeliverTransactionErrorCallback;
139 // No error callback, so fast-forward to:
140 // Transaction Step 11 - Rollback the transaction.
141 return SQLTransactionState::CleanupAfterTransactionErrorCallback;
144 SQLTransactionState SQLTransaction::deliverTransactionCallback()
146 bool shouldDeliverErrorCallback = false;
148 // Spec 4.3.2 4: Invoke the transaction callback with the new SQLTransaction object
149 OwnPtr<SQLTransactionCallback> callback = m_callbackWrapper.unwrap();
151 m_executeSqlAllowed = true;
152 shouldDeliverErrorCallback = !callback->handleEvent(this);
153 m_executeSqlAllowed = false;
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;
163 m_database->reportStartTransactionResult(0, -1, 0); // OK
167 SQLTransactionState SQLTransaction::deliverTransactionErrorCallback()
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();
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
177 if (!m_transactionError) {
178 ASSERT(m_backend->transactionError());
179 m_transactionError = SQLErrorData::create(*m_backend->transactionError());
181 ASSERT(m_transactionError);
182 RefPtrWillBeRawPtr<SQLError> error = SQLError::create(*m_transactionError);
183 errorCallback->handleEvent(error.get());
185 m_transactionError = nullptr;
188 clearCallbackWrappers();
190 // Spec 4.3.2.10: Rollback the transaction.
191 return SQLTransactionState::CleanupAfterTransactionErrorCallback;
194 SQLTransactionState SQLTransaction::deliverStatementCallback()
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;
200 AbstractSQLStatement* currentAbstractStatement = m_backend->currentStatement();
201 SQLStatement* currentStatement = static_cast<SQLStatement*>(currentAbstractStatement);
202 ASSERT(currentStatement);
204 bool result = currentStatement->performCallback(this);
206 m_executeSqlAllowed = false;
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();
213 return SQLTransactionState::RunStatements;
216 SQLTransactionState SQLTransaction::deliverQuotaIncreaseCallback()
218 ASSERT(m_backend->currentStatement());
220 bool shouldRetryCurrentStatement = m_database->transactionClient()->didExceedQuota(database());
221 m_backend->setShouldRetryCurrentStatement(shouldRetryCurrentStatement);
223 return SQLTransactionState::RunStatements;
226 SQLTransactionState SQLTransaction::deliverSuccessCallback()
228 // Spec 4.3.2.8: Deliver success callback.
229 OwnPtr<VoidCallback> successCallback = m_successCallbackWrapper.unwrap();
231 successCallback->handleEvent();
233 clearCallbackWrappers();
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;
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()
245 ASSERT_NOT_REACHED();
246 return SQLTransactionState::End;
249 SQLTransactionState SQLTransaction::sendToBackendState()
251 ASSERT(m_nextState != SQLTransactionState::Idle);
252 m_backend->requestTransitToState(m_nextState);
253 return SQLTransactionState::Idle;
256 void SQLTransaction::performPendingCallback()
258 computeNextStateAndCleanupIfNeeded();
262 void SQLTransaction::executeSQL(const String& sqlStatement, const Vector<SQLValue>& arguments, PassOwnPtr<SQLStatementCallback> callback, PassOwnPtr<SQLStatementErrorCallback> callbackError, ExceptionState& exceptionState)
264 if (!m_executeSqlAllowed) {
265 exceptionState.throwDOMException(InvalidStateError, "SQL execution is disallowed.");
269 if (!m_database->opened()) {
270 exceptionState.throwDOMException(InvalidStateError, "The database has not been opened.");
274 int permissions = DatabaseAuthorizer::ReadWriteMask;
275 if (!m_database->databaseContext()->allowDatabaseAccess())
276 permissions |= DatabaseAuthorizer::NoAccessMask;
278 permissions |= DatabaseAuthorizer::ReadOnlyMask;
280 OwnPtr<SQLStatement> statement = SQLStatement::create(m_database.get(), callback, callbackError);
281 m_backend->executeSQL(statement.release(), sqlStatement, arguments, permissions);
284 bool SQLTransaction::computeNextStateAndCleanupIfNeeded()
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);
297 WTF_LOG(StorageAPI, "Callback %s\n", nameForSQLTransactionState(m_nextState));
301 clearCallbackWrappers();
302 m_nextState = SQLTransactionState::CleanupAndTerminate;
307 void SQLTransaction::clearCallbackWrappers()
309 // Release the unneeded callbacks, to break reference cycles.
310 m_callbackWrapper.clear();
311 m_successCallbackWrapper.clear();
312 m_errorCallbackWrapper.clear();
315 PassOwnPtr<SQLTransactionErrorCallback> SQLTransaction::releaseErrorCallback()
317 return m_errorCallbackWrapper.unwrap();
320 } // namespace WebCore