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 visitor->trace(m_callbackWrapper); 77 visitor->trace(m_successCallbackWrapper); 78 visitor->trace(m_errorCallbackWrapper); 79 AbstractSQLTransaction::trace(visitor); 80 } 81 82 bool SQLTransaction::hasCallback() const 83 { 84 return m_callbackWrapper.hasCallback(); 85 } 86 87 bool SQLTransaction::hasSuccessCallback() const 88 { 89 return m_successCallbackWrapper.hasCallback(); 90 } 91 92 bool SQLTransaction::hasErrorCallback() const 93 { 94 return m_errorCallbackWrapper.hasCallback(); 95 } 96 97 void SQLTransaction::setBackend(AbstractSQLTransactionBackend* backend) 98 { 99 ASSERT(!m_backend); 100 m_backend = backend; 101 } 102 103 SQLTransaction::StateFunction SQLTransaction::stateFunctionFor(SQLTransactionState state) 104 { 105 static const StateFunction stateFunctions[] = { 106 &SQLTransaction::unreachableState, // 0. illegal 107 &SQLTransaction::unreachableState, // 1. idle 108 &SQLTransaction::unreachableState, // 2. acquireLock 109 &SQLTransaction::unreachableState, // 3. openTransactionAndPreflight 110 &SQLTransaction::sendToBackendState, // 4. runStatements 111 &SQLTransaction::unreachableState, // 5. postflightAndCommit 112 &SQLTransaction::sendToBackendState, // 6. cleanupAndTerminate 113 &SQLTransaction::sendToBackendState, // 7. cleanupAfterTransactionErrorCallback 114 &SQLTransaction::deliverTransactionCallback, // 8. 115 &SQLTransaction::deliverTransactionErrorCallback, // 9. 116 &SQLTransaction::deliverStatementCallback, // 10. 117 &SQLTransaction::deliverQuotaIncreaseCallback, // 11. 118 &SQLTransaction::deliverSuccessCallback // 12. 119 }; 120 121 ASSERT(WTF_ARRAY_LENGTH(stateFunctions) == static_cast<int>(SQLTransactionState::NumberOfStates)); 122 ASSERT(state < SQLTransactionState::NumberOfStates); 123 124 return stateFunctions[static_cast<int>(state)]; 125 } 126 127 // requestTransitToState() can be called from the backend. Hence, it should 128 // NOT be modifying SQLTransactionBackend in general. The only safe field to 129 // modify is m_requestedState which is meant for this purpose. 130 void SQLTransaction::requestTransitToState(SQLTransactionState nextState) 131 { 132 WTF_LOG(StorageAPI, "Scheduling %s for transaction %p\n", nameForSQLTransactionState(nextState), this); 133 m_requestedState = nextState; 134 m_database->scheduleTransactionCallback(this); 135 } 136 137 SQLTransactionState SQLTransaction::nextStateForTransactionError() 138 { 139 ASSERT(m_transactionError); 140 if (m_errorCallbackWrapper.hasCallback()) 141 return SQLTransactionState::DeliverTransactionErrorCallback; 142 143 // No error callback, so fast-forward to: 144 // Transaction Step 11 - Rollback the transaction. 145 return SQLTransactionState::CleanupAfterTransactionErrorCallback; 146 } 147 148 SQLTransactionState SQLTransaction::deliverTransactionCallback() 149 { 150 bool shouldDeliverErrorCallback = false; 151 152 // Spec 4.3.2 4: Invoke the transaction callback with the new SQLTransaction object 153 OwnPtr<SQLTransactionCallback> callback = m_callbackWrapper.unwrap(); 154 if (callback) { 155 m_executeSqlAllowed = true; 156 shouldDeliverErrorCallback = !callback->handleEvent(this); 157 m_executeSqlAllowed = false; 158 } 159 160 // Spec 4.3.2 5: If the transaction callback was null or raised an exception, jump to the error callback 161 SQLTransactionState nextState = SQLTransactionState::RunStatements; 162 if (shouldDeliverErrorCallback) { 163 m_database->reportStartTransactionResult(5, SQLError::UNKNOWN_ERR, 0); 164 m_transactionError = SQLErrorData::create(SQLError::UNKNOWN_ERR, "the SQLTransactionCallback was null or threw an exception"); 165 nextState = SQLTransactionState::DeliverTransactionErrorCallback; 166 } 167 m_database->reportStartTransactionResult(0, -1, 0); // OK 168 return nextState; 169 } 170 171 SQLTransactionState SQLTransaction::deliverTransactionErrorCallback() 172 { 173 // Spec 4.3.2.10: If exists, invoke error callback with the last 174 // error to have occurred in this transaction. 175 OwnPtr<SQLTransactionErrorCallback> errorCallback = m_errorCallbackWrapper.unwrap(); 176 if (errorCallback) { 177 // If we get here with an empty m_transactionError, then the backend 178 // must be waiting in the idle state waiting for this state to finish. 179 // Hence, it's thread safe to fetch the backend transactionError without 180 // a lock. 181 if (!m_transactionError) { 182 ASSERT(m_backend->transactionError()); 183 m_transactionError = SQLErrorData::create(*m_backend->transactionError()); 184 } 185 ASSERT(m_transactionError); 186 RefPtrWillBeRawPtr<SQLError> error = SQLError::create(*m_transactionError); 187 errorCallback->handleEvent(error.get()); 188 189 m_transactionError = nullptr; 190 } 191 192 clearCallbackWrappers(); 193 194 // Spec 4.3.2.10: Rollback the transaction. 195 return SQLTransactionState::CleanupAfterTransactionErrorCallback; 196 } 197 198 SQLTransactionState SQLTransaction::deliverStatementCallback() 199 { 200 // Spec 4.3.2.6.6 and 4.3.2.6.3: If the statement callback went wrong, jump to the transaction error callback 201 // Otherwise, continue to loop through the statement queue 202 m_executeSqlAllowed = true; 203 204 AbstractSQLStatement* currentAbstractStatement = m_backend->currentStatement(); 205 SQLStatement* currentStatement = static_cast<SQLStatement*>(currentAbstractStatement); 206 ASSERT(currentStatement); 207 208 bool result = currentStatement->performCallback(this); 209 210 m_executeSqlAllowed = false; 211 212 if (result) { 213 m_database->reportCommitTransactionResult(2, SQLError::UNKNOWN_ERR, 0); 214 m_transactionError = SQLErrorData::create(SQLError::UNKNOWN_ERR, "the statement callback raised an exception or statement error callback did not return false"); 215 return nextStateForTransactionError(); 216 } 217 return SQLTransactionState::RunStatements; 218 } 219 220 SQLTransactionState SQLTransaction::deliverQuotaIncreaseCallback() 221 { 222 ASSERT(m_backend->currentStatement()); 223 224 bool shouldRetryCurrentStatement = m_database->transactionClient()->didExceedQuota(database()); 225 m_backend->setShouldRetryCurrentStatement(shouldRetryCurrentStatement); 226 227 return SQLTransactionState::RunStatements; 228 } 229 230 SQLTransactionState SQLTransaction::deliverSuccessCallback() 231 { 232 // Spec 4.3.2.8: Deliver success callback. 233 OwnPtr<VoidCallback> successCallback = m_successCallbackWrapper.unwrap(); 234 if (successCallback) 235 successCallback->handleEvent(); 236 237 clearCallbackWrappers(); 238 239 // Schedule a "post-success callback" step to return control to the database thread in case there 240 // are further transactions queued up for this Database 241 return SQLTransactionState::CleanupAndTerminate; 242 } 243 244 // This state function is used as a stub function to plug unimplemented states 245 // in the state dispatch table. They are unimplemented because they should 246 // never be reached in the course of correct execution. 247 SQLTransactionState SQLTransaction::unreachableState() 248 { 249 ASSERT_NOT_REACHED(); 250 return SQLTransactionState::End; 251 } 252 253 SQLTransactionState SQLTransaction::sendToBackendState() 254 { 255 ASSERT(m_nextState != SQLTransactionState::Idle); 256 m_backend->requestTransitToState(m_nextState); 257 return SQLTransactionState::Idle; 258 } 259 260 void SQLTransaction::performPendingCallback() 261 { 262 computeNextStateAndCleanupIfNeeded(); 263 runStateMachine(); 264 } 265 266 void SQLTransaction::executeSQL(const String& sqlStatement, const Vector<SQLValue>& arguments, PassOwnPtr<SQLStatementCallback> callback, PassOwnPtr<SQLStatementErrorCallback> callbackError, ExceptionState& exceptionState) 267 { 268 if (!m_executeSqlAllowed) { 269 exceptionState.throwDOMException(InvalidStateError, "SQL execution is disallowed."); 270 return; 271 } 272 273 if (!m_database->opened()) { 274 exceptionState.throwDOMException(InvalidStateError, "The database has not been opened."); 275 return; 276 } 277 278 int permissions = DatabaseAuthorizer::ReadWriteMask; 279 if (!m_database->databaseContext()->allowDatabaseAccess()) 280 permissions |= DatabaseAuthorizer::NoAccessMask; 281 else if (m_readOnly) 282 permissions |= DatabaseAuthorizer::ReadOnlyMask; 283 284 OwnPtrWillBeRawPtr<SQLStatement> statement = SQLStatement::create(m_database.get(), callback, callbackError); 285 m_backend->executeSQL(statement.release(), sqlStatement, arguments, permissions); 286 } 287 288 bool SQLTransaction::computeNextStateAndCleanupIfNeeded() 289 { 290 // Only honor the requested state transition if we're not supposed to be 291 // cleaning up and shutting down: 292 if (m_database->opened() && !m_database->isInterrupted()) { 293 setStateToRequestedState(); 294 ASSERT(m_nextState == SQLTransactionState::End 295 || m_nextState == SQLTransactionState::DeliverTransactionCallback 296 || m_nextState == SQLTransactionState::DeliverTransactionErrorCallback 297 || m_nextState == SQLTransactionState::DeliverStatementCallback 298 || m_nextState == SQLTransactionState::DeliverQuotaIncreaseCallback 299 || m_nextState == SQLTransactionState::DeliverSuccessCallback); 300 301 WTF_LOG(StorageAPI, "Callback %s\n", nameForSQLTransactionState(m_nextState)); 302 return false; 303 } 304 305 clearCallbackWrappers(); 306 m_nextState = SQLTransactionState::CleanupAndTerminate; 307 308 return true; 309 } 310 311 void SQLTransaction::clearCallbackWrappers() 312 { 313 // Release the unneeded callbacks, to break reference cycles. 314 m_callbackWrapper.clear(); 315 m_successCallbackWrapper.clear(); 316 m_errorCallbackWrapper.clear(); 317 } 318 319 PassOwnPtr<SQLTransactionErrorCallback> SQLTransaction::releaseErrorCallback() 320 { 321 return m_errorCallbackWrapper.unwrap(); 322 } 323 324 } // namespace WebCore 325