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/SQLTransactionBackend.h" 31 32 #include "core/platform/Logging.h" 33 #include "core/platform/sql/SQLValue.h" 34 #include "core/platform/sql/SQLiteTransaction.h" 35 #include "modules/webdatabase/AbstractSQLTransaction.h" 36 #include "modules/webdatabase/Database.h" // FIXME: Should only be used in the frontend. 37 #include "modules/webdatabase/DatabaseAuthorizer.h" 38 #include "modules/webdatabase/DatabaseBackend.h" 39 #include "modules/webdatabase/DatabaseBackendContext.h" 40 #include "modules/webdatabase/DatabaseThread.h" 41 #include "modules/webdatabase/DatabaseTracker.h" 42 #include "modules/webdatabase/SQLError.h" 43 #include "modules/webdatabase/SQLStatementBackend.h" 44 #include "modules/webdatabase/SQLTransactionClient.h" 45 #include "modules/webdatabase/SQLTransactionCoordinator.h" 46 #include "wtf/StdLibExtras.h" 47 #include "wtf/text/WTFString.h" 48 49 50 // How does a SQLTransaction work? 51 // ============================== 52 // The SQLTransaction is a state machine that executes a series of states / steps. 53 // 54 // The work of the transaction states are defined in section of 4.3.2 of the 55 // webdatabase spec: http://dev.w3.org/html5/webdatabase/#processing-model 56 // 57 // the State Transition Graph at a glance: 58 // ====================================== 59 // 60 // Backend . Frontend 61 // (works with SQLiteDatabase) . (works with Script) 62 // =========================== . =================== 63 // . 64 // 1. Idle . 65 // v . 66 // 2. AcquireLock . 67 // v . 68 // 3. OpenTransactionAndPreflight ------------------------------------------. 69 // | . | 70 // `-------------------------------> 8. DeliverTransactionCallback --. | 71 // . | v v 72 // ,-------------------------------------' 9. DeliverTransactionErrorCallback + 73 // | . ^ ^ ^ | 74 // v . | | | | 75 // 4. RunStatements -----------------------------------------------------' | | | 76 // | ^ ^ | ^ | . | | | 77 // |--------' | | | `------------> 10. DeliverStatementCallback +-----' | | 78 // | | | `---------------------------------------------' | | 79 // | | `-----------------> 11. DeliverQuotaIncreaseCallback + | | 80 // | `-----------------------------------------------------' | | 81 // v . | | 82 // 5. PostflightAndCommit --+--------------------------------------------------' | 83 // |----------> 12. DeliverSuccessCallback + | 84 // ,--------------------' . | | 85 // v . | | 86 // 6. CleanupAndTerminate <-----------------------------------------' | 87 // v ^ . | 88 // 0. End | . | 89 // | . | 90 // 7: CleanupAfterTransactionErrorCallback <----------------------------' 91 // . 92 // 93 // the States and State Transitions: 94 // ================================ 95 // 0. SQLTransactionState::End 96 // - the end state. 97 // 98 // 1. SQLTransactionState::Idle 99 // - placeholder state while waiting on frontend/backend, etc. See comment on 100 // "State transitions between SQLTransaction and SQLTransactionBackend" 101 // below. 102 // 103 // 2. SQLTransactionState::AcquireLock (runs in backend) 104 // - this is the start state. 105 // - acquire the "lock". 106 // - on "lock" acquisition, goto SQLTransactionState::OpenTransactionAndPreflight. 107 // 108 // 3. SQLTransactionState::openTransactionAndPreflight (runs in backend) 109 // - Sets up an SQLiteTransaction. 110 // - begin the SQLiteTransaction. 111 // - call the SQLTransactionWrapper preflight if available. 112 // - schedule script callback. 113 // - on error, goto SQLTransactionState::DeliverTransactionErrorCallback. 114 // - goto SQLTransactionState::DeliverTransactionCallback. 115 // 116 // 4. SQLTransactionState::DeliverTransactionCallback (runs in frontend) 117 // - invoke the script function callback() if available. 118 // - on error, goto SQLTransactionState::DeliverTransactionErrorCallback. 119 // - goto SQLTransactionState::RunStatements. 120 // 121 // 5. SQLTransactionState::DeliverTransactionErrorCallback (runs in frontend) 122 // - invoke the script function errorCallback if available. 123 // - goto SQLTransactionState::CleanupAfterTransactionErrorCallback. 124 // 125 // 6. SQLTransactionState::RunStatements (runs in backend) 126 // - while there are statements { 127 // - run a statement. 128 // - if statementCallback is available, goto SQLTransactionState::DeliverStatementCallback. 129 // - on error, 130 // goto SQLTransactionState::DeliverQuotaIncreaseCallback, or 131 // goto SQLTransactionState::DeliverStatementCallback, or 132 // goto SQLTransactionState::deliverTransactionErrorCallback. 133 // } 134 // - goto SQLTransactionState::PostflightAndCommit. 135 // 136 // 7. SQLTransactionState::DeliverStatementCallback (runs in frontend) 137 // - invoke script statement callback (assume available). 138 // - on error, goto SQLTransactionState::DeliverTransactionErrorCallback. 139 // - goto SQLTransactionState::RunStatements. 140 // 141 // 8. SQLTransactionState::DeliverQuotaIncreaseCallback (runs in frontend) 142 // - give client a chance to increase the quota. 143 // - goto SQLTransactionState::RunStatements. 144 // 145 // 9. SQLTransactionState::PostflightAndCommit (runs in backend) 146 // - call the SQLTransactionWrapper postflight if available. 147 // - commit the SQLiteTansaction. 148 // - on error, goto SQLTransactionState::DeliverTransactionErrorCallback. 149 // - if successCallback is available, goto SQLTransactionState::DeliverSuccessCallback. 150 // else goto SQLTransactionState::CleanupAndTerminate. 151 // 152 // 10. SQLTransactionState::DeliverSuccessCallback (runs in frontend) 153 // - invoke the script function successCallback() if available. 154 // - goto SQLTransactionState::CleanupAndTerminate. 155 // 156 // 11. SQLTransactionState::CleanupAndTerminate (runs in backend) 157 // - stop and clear the SQLiteTransaction. 158 // - release the "lock". 159 // - goto SQLTransactionState::End. 160 // 161 // 12. SQLTransactionState::CleanupAfterTransactionErrorCallback (runs in backend) 162 // - rollback the SQLiteTransaction. 163 // - goto SQLTransactionState::CleanupAndTerminate. 164 // 165 // State transitions between SQLTransaction and SQLTransactionBackend 166 // ================================================================== 167 // As shown above, there are state transitions that crosses the boundary between 168 // the frontend and backend. For example, 169 // 170 // OpenTransactionAndPreflight (state 3 in the backend) 171 // transitions to DeliverTransactionCallback (state 8 in the frontend), 172 // which in turn transitions to RunStatements (state 4 in the backend). 173 // 174 // This cross boundary transition is done by posting transition requests to the 175 // other side and letting the other side's state machine execute the state 176 // transition in the appropriate thread (i.e. the script thread for the frontend, 177 // and the database thread for the backend). 178 // 179 // Logically, the state transitions work as shown in the graph above. But 180 // physically, the transition mechanism uses the Idle state (both in the frontend 181 // and backend) as a waiting state for further activity. For example, taking a 182 // closer look at the 3 state transition example above, what actually happens 183 // is as follows: 184 // 185 // Step 1: 186 // ====== 187 // In the frontend thread: 188 // - waiting quietly is Idle. Not doing any work. 189 // 190 // In the backend: 191 // - is in OpenTransactionAndPreflight, and doing its work. 192 // - when done, it transits to the backend DeliverTransactionCallback. 193 // - the backend DeliverTransactionCallback sends a request to the frontend 194 // to transit to DeliverTransactionCallback, and then itself transits to 195 // Idle. 196 // 197 // Step 2: 198 // ====== 199 // In the frontend thread: 200 // - transits to DeliverTransactionCallback and does its work. 201 // - when done, it transits to the frontend RunStatements. 202 // - the frontend RunStatements sends a request to the backend to transit 203 // to RunStatements, and then itself transits to Idle. 204 // 205 // In the backend: 206 // - waiting quietly in Idle. 207 // 208 // Step 3: 209 // ====== 210 // In the frontend thread: 211 // - waiting quietly is Idle. Not doing any work. 212 // 213 // In the backend: 214 // - transits to RunStatements, and does its work. 215 // ... 216 // 217 // So, when the frontend or backend are not active, they will park themselves in 218 // their Idle states. This means their m_nextState is set to Idle, but they never 219 // actually run the corresponding state function. Note: for both the frontend and 220 // backend, the state function for Idle is unreachableState(). 221 // 222 // The states that send a request to their peer across the front/back boundary 223 // are implemented with just 2 functions: SQLTransaction::sendToBackendState() 224 // and SQLTransactionBackend::sendToFrontendState(). These state functions do 225 // nothing but sends a request to the other side to transit to the current 226 // state (indicated by m_nextState), and then transits itself to the Idle state 227 // to wait for further action. 228 229 230 // The Life-Cycle of a SQLTransaction i.e. Who's keeping the SQLTransaction alive? 231 // ============================================================================== 232 // The RefPtr chain goes something like this: 233 // 234 // At birth (in DatabaseBackend::runTransaction()): 235 // ==================================================== 236 // DatabaseBackend // Deque<RefPtr<SQLTransactionBackend> > m_transactionQueue points to ... 237 // --> SQLTransactionBackend // RefPtr<SQLTransaction> m_frontend points to ... 238 // --> SQLTransaction // RefPtr<SQLTransactionBackend> m_backend points to ... 239 // --> SQLTransactionBackend // which is a circular reference. 240 // 241 // Note: there's a circular reference between the SQLTransaction front-end and 242 // back-end. This circular reference is established in the constructor of the 243 // SQLTransactionBackend. The circular reference will be broken by calling 244 // doCleanup() to nullify m_frontend. This is done at the end of the transaction's 245 // clean up state (i.e. when the transaction should no longer be in use thereafter), 246 // or if the database was interrupted. See comments on "What happens if a transaction 247 // is interrupted?" below for details. 248 // 249 // After scheduling the transaction with the DatabaseThread (DatabaseBackend::scheduleTransaction()): 250 // ====================================================================================================== 251 // DatabaseThread // MessageQueue<DatabaseTask> m_queue points to ... 252 // --> DatabaseTransactionTask // RefPtr<SQLTransactionBackend> m_transaction points to ... 253 // --> SQLTransactionBackend // RefPtr<SQLTransaction> m_frontend points to ... 254 // --> SQLTransaction // RefPtr<SQLTransactionBackend> m_backend points to ... 255 // --> SQLTransactionBackend // which is a circular reference. 256 // 257 // When executing the transaction (in DatabaseThread::databaseThread()): 258 // ==================================================================== 259 // OwnPtr<DatabaseTask> task; // points to ... 260 // --> DatabaseTransactionTask // RefPtr<SQLTransactionBackend> m_transaction points to ... 261 // --> SQLTransactionBackend // RefPtr<SQLTransaction> m_frontend; 262 // --> SQLTransaction // RefPtr<SQLTransactionBackend> m_backend points to ... 263 // --> SQLTransactionBackend // which is a circular reference. 264 // 265 // At the end of cleanupAndTerminate(): 266 // =================================== 267 // At the end of the cleanup state, the SQLTransactionBackend::m_frontend is nullified. 268 // If by then, a JSObject wrapper is referring to the SQLTransaction, then the reference 269 // chain looks like this: 270 // 271 // JSObjectWrapper 272 // --> SQLTransaction // in RefPtr<SQLTransactionBackend> m_backend points to ... 273 // --> SQLTransactionBackend // which no longer points back to its SQLTransaction. 274 // 275 // When the GC collects the corresponding JSObject, the above chain will be cleaned up 276 // and deleted. 277 // 278 // If there is no JSObject wrapper referring to the SQLTransaction when the cleanup 279 // states nullify SQLTransactionBackend::m_frontend, the SQLTransaction will deleted then. 280 // However, there will still be a DatabaseTask pointing to the SQLTransactionBackend (see 281 // the "When executing the transaction" chain above). This will keep the 282 // SQLTransactionBackend alive until DatabaseThread::databaseThread() releases its 283 // task OwnPtr. 284 // 285 // What happens if a transaction is interrupted? 286 // ============================================ 287 // If the transaction is interrupted half way, it won't get to run to state 288 // CleanupAndTerminate, and hence, would not have called SQLTransactionBackend's 289 // doCleanup(). doCleanup() is where we nullify SQLTransactionBackend::m_frontend 290 // to break the reference cycle between the frontend and backend. Hence, we need 291 // to cleanup the transaction by other means. 292 // 293 // Note: calling SQLTransactionBackend::notifyDatabaseThreadIsShuttingDown() 294 // is effectively the same as calling SQLTransactionBackend::doClean(). 295 // 296 // In terms of who needs to call doCleanup(), there are 5 phases in the 297 // SQLTransactionBackend life-cycle. These are the phases and how the clean 298 // up is done: 299 // 300 // Phase 1. After Birth, before scheduling 301 // 302 // - To clean up, DatabaseThread::databaseThread() will call 303 // DatabaseBackend::close() during its shutdown. 304 // - DatabaseBackend::close() will iterate 305 // DatabaseBackend::m_transactionQueue and call 306 // notifyDatabaseThreadIsShuttingDown() on each transaction there. 307 // 308 // Phase 2. After scheduling, before state AcquireLock 309 // 310 // - If the interruption occures before the DatabaseTransactionTask is 311 // scheduled in DatabaseThread::m_queue but hasn't gotten to execute 312 // (i.e. DatabaseTransactionTask::performTask() has not been called), 313 // then the DatabaseTransactionTask may get destructed before it ever 314 // gets to execute. 315 // - To clean up, the destructor will check if the task's m_wasExecuted is 316 // set. If not, it will call notifyDatabaseThreadIsShuttingDown() on 317 // the task's transaction. 318 // 319 // Phase 3. After state AcquireLock, before "lockAcquired" 320 // 321 // - In this phase, the transaction would have been added to the 322 // SQLTransactionCoordinator's CoordinationInfo's pendingTransactions. 323 // - To clean up, during shutdown, DatabaseThread::databaseThread() calls 324 // SQLTransactionCoordinator::shutdown(), which calls 325 // notifyDatabaseThreadIsShuttingDown(). 326 // 327 // Phase 4: After "lockAcquired", before state CleanupAndTerminate 328 // 329 // - In this phase, the transaction would have been added either to the 330 // SQLTransactionCoordinator's CoordinationInfo's activeWriteTransaction 331 // or activeReadTransactions. 332 // - To clean up, during shutdown, DatabaseThread::databaseThread() calls 333 // SQLTransactionCoordinator::shutdown(), which calls 334 // notifyDatabaseThreadIsShuttingDown(). 335 // 336 // Phase 5: After state CleanupAndTerminate 337 // 338 // - This is how a transaction ends normally. 339 // - state CleanupAndTerminate calls doCleanup(). 340 341 342 // There's no way of knowing exactly how much more space will be required when a statement hits the quota limit. 343 // For now, we'll arbitrarily choose currentQuota + 1mb. 344 // In the future we decide to track if a size increase wasn't enough, and ask for larger-and-larger increases until its enough. 345 static const int DefaultQuotaSizeIncrease = 1048576; 346 347 namespace WebCore { 348 349 PassRefPtr<SQLTransactionBackend> SQLTransactionBackend::create(DatabaseBackend* db, 350 PassRefPtr<AbstractSQLTransaction> frontend, PassRefPtr<SQLTransactionWrapper> wrapper, bool readOnly) 351 { 352 return adoptRef(new SQLTransactionBackend(db, frontend, wrapper, readOnly)); 353 } 354 355 SQLTransactionBackend::SQLTransactionBackend(DatabaseBackend* db, 356 PassRefPtr<AbstractSQLTransaction> frontend, PassRefPtr<SQLTransactionWrapper> wrapper, bool readOnly) 357 : m_frontend(frontend) 358 , m_database(db) 359 , m_wrapper(wrapper) 360 , m_hasCallback(m_frontend->hasCallback()) 361 , m_hasSuccessCallback(m_frontend->hasSuccessCallback()) 362 , m_hasErrorCallback(m_frontend->hasErrorCallback()) 363 , m_shouldRetryCurrentStatement(false) 364 , m_modifiedDatabase(false) 365 , m_lockAcquired(false) 366 , m_readOnly(readOnly) 367 , m_hasVersionMismatch(false) 368 { 369 ASSERT(m_database); 370 m_frontend->setBackend(this); 371 m_requestedState = SQLTransactionState::AcquireLock; 372 } 373 374 SQLTransactionBackend::~SQLTransactionBackend() 375 { 376 ASSERT(!m_sqliteTransaction); 377 } 378 379 void SQLTransactionBackend::doCleanup() 380 { 381 if (!m_frontend) 382 return; 383 m_frontend = 0; // Break the reference cycle. See comment about the life-cycle above. 384 385 ASSERT(currentThread() == database()->databaseContext()->databaseThread()->getThreadID()); 386 387 MutexLocker locker(m_statementMutex); 388 m_statementQueue.clear(); 389 390 if (m_sqliteTransaction) { 391 // In the event we got here because of an interruption or error (i.e. if 392 // the transaction is in progress), we should roll it back here. Clearing 393 // m_sqliteTransaction invokes SQLiteTransaction's destructor which does 394 // just that. We might as well do this unconditionally and free up its 395 // resources because we're already terminating. 396 m_sqliteTransaction.clear(); 397 } 398 399 // Release the lock on this database 400 if (m_lockAcquired) 401 m_database->transactionCoordinator()->releaseLock(this); 402 403 // Do some aggresive clean up here except for m_database. 404 // 405 // We can't clear m_database here because the frontend may asynchronously 406 // invoke SQLTransactionBackend::requestTransitToState(), and that function 407 // uses m_database to schedule a state transition. This may occur because 408 // the frontend (being in another thread) may already be on the way to 409 // requesting our next state before it detects an interruption. 410 // 411 // There is no harm in letting it finish making the request. It'll set 412 // m_requestedState, but we won't execute a transition to that state because 413 // we've already shut down the transaction. 414 // 415 // We also can't clear m_currentStatementBackend and m_transactionError. 416 // m_currentStatementBackend may be accessed asynchronously by the 417 // frontend's deliverStatementCallback() state. Similarly, 418 // m_transactionError may be accessed by deliverTransactionErrorCallback(). 419 // This occurs if requests for transition to those states have already been 420 // registered with the frontend just prior to a clean up request arriving. 421 // 422 // So instead, let our destructor handle their clean up since this 423 // SQLTransactionBackend is guaranteed to not destruct until the frontend 424 // is also destructing. 425 426 m_wrapper = 0; 427 } 428 429 AbstractSQLStatement* SQLTransactionBackend::currentStatement() 430 { 431 return m_currentStatementBackend->frontend(); 432 } 433 434 PassRefPtr<SQLError> SQLTransactionBackend::transactionError() 435 { 436 return m_transactionError; 437 } 438 439 void SQLTransactionBackend::setShouldRetryCurrentStatement(bool shouldRetry) 440 { 441 ASSERT(!m_shouldRetryCurrentStatement); 442 m_shouldRetryCurrentStatement = shouldRetry; 443 } 444 445 SQLTransactionBackend::StateFunction SQLTransactionBackend::stateFunctionFor(SQLTransactionState state) 446 { 447 static const StateFunction stateFunctions[] = { 448 &SQLTransactionBackend::unreachableState, // 0. end 449 &SQLTransactionBackend::unreachableState, // 1. idle 450 &SQLTransactionBackend::acquireLock, // 2. 451 &SQLTransactionBackend::openTransactionAndPreflight, // 3. 452 &SQLTransactionBackend::runStatements, // 4. 453 &SQLTransactionBackend::postflightAndCommit, // 5. 454 &SQLTransactionBackend::cleanupAndTerminate, // 6. 455 &SQLTransactionBackend::cleanupAfterTransactionErrorCallback, // 7. 456 &SQLTransactionBackend::sendToFrontendState, // 8. deliverTransactionCallback 457 &SQLTransactionBackend::sendToFrontendState, // 9. deliverTransactionErrorCallback 458 &SQLTransactionBackend::sendToFrontendState, // 10. deliverStatementCallback 459 &SQLTransactionBackend::sendToFrontendState, // 11. deliverQuotaIncreaseCallback 460 &SQLTransactionBackend::sendToFrontendState // 12. deliverSuccessCallback 461 }; 462 463 ASSERT(WTF_ARRAY_LENGTH(stateFunctions) == static_cast<int>(SQLTransactionState::NumberOfStates)); 464 ASSERT(state < SQLTransactionState::NumberOfStates); 465 466 return stateFunctions[static_cast<int>(state)]; 467 } 468 469 void SQLTransactionBackend::enqueueStatementBackend(PassRefPtr<SQLStatementBackend> statementBackend) 470 { 471 MutexLocker locker(m_statementMutex); 472 m_statementQueue.append(statementBackend); 473 } 474 475 void SQLTransactionBackend::computeNextStateAndCleanupIfNeeded() 476 { 477 // Only honor the requested state transition if we're not supposed to be 478 // cleaning up and shutting down: 479 if (m_database->opened() && !m_database->isInterrupted()) { 480 setStateToRequestedState(); 481 ASSERT(m_nextState == SQLTransactionState::AcquireLock 482 || m_nextState == SQLTransactionState::OpenTransactionAndPreflight 483 || m_nextState == SQLTransactionState::RunStatements 484 || m_nextState == SQLTransactionState::PostflightAndCommit 485 || m_nextState == SQLTransactionState::CleanupAndTerminate 486 || m_nextState == SQLTransactionState::CleanupAfterTransactionErrorCallback); 487 488 LOG(StorageAPI, "State %s\n", nameForSQLTransactionState(m_nextState)); 489 return; 490 } 491 492 // If we get here, then we should be shutting down. Do clean up if needed: 493 if (m_nextState == SQLTransactionState::End) 494 return; 495 m_nextState = SQLTransactionState::End; 496 497 // If the database was stopped, don't do anything and cancel queued work 498 LOG(StorageAPI, "Database was stopped or interrupted - cancelling work for this transaction"); 499 500 // The current SQLite transaction should be stopped, as well 501 if (m_sqliteTransaction) { 502 m_sqliteTransaction->stop(); 503 m_sqliteTransaction.clear(); 504 } 505 506 // Terminate the frontend state machine. This also gets the frontend to 507 // call computeNextStateAndCleanupIfNeeded() and clear its wrappers 508 // if needed. 509 m_frontend->requestTransitToState(SQLTransactionState::End); 510 511 // Redirect to the end state to abort, clean up, and end the transaction. 512 doCleanup(); 513 } 514 515 void SQLTransactionBackend::performNextStep() 516 { 517 computeNextStateAndCleanupIfNeeded(); 518 runStateMachine(); 519 } 520 521 void SQLTransactionBackend::executeSQL(PassOwnPtr<AbstractSQLStatement> statement, 522 const String& sqlStatement, const Vector<SQLValue>& arguments, int permissions) 523 { 524 RefPtr<SQLStatementBackend> statementBackend; 525 statementBackend = SQLStatementBackend::create(statement, sqlStatement, arguments, permissions); 526 527 if (Database::from(m_database.get())->deleted()) 528 statementBackend->setDatabaseDeletedError(m_database.get()); 529 530 enqueueStatementBackend(statementBackend); 531 } 532 533 void SQLTransactionBackend::notifyDatabaseThreadIsShuttingDown() 534 { 535 ASSERT(currentThread() == database()->databaseContext()->databaseThread()->getThreadID()); 536 537 // If the transaction is in progress, we should roll it back here, since this 538 // is our last opportunity to do something related to this transaction on the 539 // DB thread. Amongst other work, doCleanup() will clear m_sqliteTransaction 540 // which invokes SQLiteTransaction's destructor, which will do the roll back 541 // if necessary. 542 doCleanup(); 543 } 544 545 SQLTransactionState SQLTransactionBackend::acquireLock() 546 { 547 m_database->transactionCoordinator()->acquireLock(this); 548 return SQLTransactionState::Idle; 549 } 550 551 void SQLTransactionBackend::lockAcquired() 552 { 553 m_lockAcquired = true; 554 requestTransitToState(SQLTransactionState::OpenTransactionAndPreflight); 555 } 556 557 SQLTransactionState SQLTransactionBackend::openTransactionAndPreflight() 558 { 559 ASSERT(!m_database->sqliteDatabase().transactionInProgress()); 560 ASSERT(m_lockAcquired); 561 562 LOG(StorageAPI, "Opening and preflighting transaction %p", this); 563 564 // If the database was deleted, jump to the error callback 565 if (Database::from(m_database.get())->deleted()) { 566 m_database->reportStartTransactionResult(1, SQLError::UNKNOWN_ERR, 0); 567 m_transactionError = SQLError::create(SQLError::UNKNOWN_ERR, "unable to open a transaction, because the user deleted the database"); 568 return nextStateForTransactionError(); 569 } 570 571 // Set the maximum usage for this transaction if this transactions is not read-only 572 if (!m_readOnly) 573 m_database->sqliteDatabase().setMaximumSize(m_database->maximumSize()); 574 575 ASSERT(!m_sqliteTransaction); 576 m_sqliteTransaction = adoptPtr(new SQLiteTransaction(m_database->sqliteDatabase(), m_readOnly)); 577 578 m_database->resetDeletes(); 579 m_database->disableAuthorizer(); 580 m_sqliteTransaction->begin(); 581 m_database->enableAuthorizer(); 582 583 // Spec 4.3.2.1+2: Open a transaction to the database, jumping to the error callback if that fails 584 if (!m_sqliteTransaction->inProgress()) { 585 ASSERT(!m_database->sqliteDatabase().transactionInProgress()); 586 m_database->reportStartTransactionResult(2, SQLError::DATABASE_ERR, m_database->sqliteDatabase().lastError()); 587 m_transactionError = SQLError::create(SQLError::DATABASE_ERR, "unable to begin transaction", 588 m_database->sqliteDatabase().lastError(), m_database->sqliteDatabase().lastErrorMsg()); 589 m_sqliteTransaction.clear(); 590 return nextStateForTransactionError(); 591 } 592 593 // Note: We intentionally retrieve the actual version even with an empty expected version. 594 // In multi-process browsers, we take this opportinutiy to update the cached value for 595 // the actual version. In single-process browsers, this is just a map lookup. 596 String actualVersion; 597 if (!m_database->getActualVersionForTransaction(actualVersion)) { 598 m_database->reportStartTransactionResult(3, SQLError::DATABASE_ERR, m_database->sqliteDatabase().lastError()); 599 m_transactionError = SQLError::create(SQLError::DATABASE_ERR, "unable to read version", 600 m_database->sqliteDatabase().lastError(), m_database->sqliteDatabase().lastErrorMsg()); 601 m_database->disableAuthorizer(); 602 m_sqliteTransaction.clear(); 603 m_database->enableAuthorizer(); 604 return nextStateForTransactionError(); 605 } 606 m_hasVersionMismatch = !m_database->expectedVersion().isEmpty() && (m_database->expectedVersion() != actualVersion); 607 608 // Spec 4.3.2.3: Perform preflight steps, jumping to the error callback if they fail 609 if (m_wrapper && !m_wrapper->performPreflight(this)) { 610 m_database->disableAuthorizer(); 611 m_sqliteTransaction.clear(); 612 m_database->enableAuthorizer(); 613 m_transactionError = m_wrapper->sqlError(); 614 if (!m_transactionError) { 615 m_database->reportStartTransactionResult(4, SQLError::UNKNOWN_ERR, 0); 616 m_transactionError = SQLError::create(SQLError::UNKNOWN_ERR, "unknown error occurred during transaction preflight"); 617 } 618 return nextStateForTransactionError(); 619 } 620 621 // Spec 4.3.2.4: Invoke the transaction callback with the new SQLTransaction object 622 if (m_hasCallback) 623 return SQLTransactionState::DeliverTransactionCallback; 624 625 // If we have no callback to make, skip pass to the state after: 626 return SQLTransactionState::RunStatements; 627 } 628 629 SQLTransactionState SQLTransactionBackend::runStatements() 630 { 631 ASSERT(m_lockAcquired); 632 SQLTransactionState nextState; 633 634 // If there is a series of statements queued up that are all successful and have no associated 635 // SQLStatementCallback objects, then we can burn through the queue 636 do { 637 if (m_shouldRetryCurrentStatement && !m_sqliteTransaction->wasRolledBackBySqlite()) { 638 m_shouldRetryCurrentStatement = false; 639 // FIXME - Another place that needs fixing up after <rdar://problem/5628468> is addressed. 640 // See ::openTransactionAndPreflight() for discussion 641 642 // Reset the maximum size here, as it was increased to allow us to retry this statement. 643 // m_shouldRetryCurrentStatement is set to true only when a statement exceeds 644 // the quota, which can happen only in a read-write transaction. Therefore, there 645 // is no need to check here if the transaction is read-write. 646 m_database->sqliteDatabase().setMaximumSize(m_database->maximumSize()); 647 } else { 648 // If the current statement has already been run, failed due to quota constraints, and we're not retrying it, 649 // that means it ended in an error. Handle it now 650 if (m_currentStatementBackend && m_currentStatementBackend->lastExecutionFailedDueToQuota()) { 651 return nextStateForCurrentStatementError(); 652 } 653 654 // Otherwise, advance to the next statement 655 getNextStatement(); 656 } 657 nextState = runCurrentStatementAndGetNextState(); 658 } while (nextState == SQLTransactionState::RunStatements); 659 660 return nextState; 661 } 662 663 void SQLTransactionBackend::getNextStatement() 664 { 665 m_currentStatementBackend = 0; 666 667 MutexLocker locker(m_statementMutex); 668 if (!m_statementQueue.isEmpty()) 669 m_currentStatementBackend = m_statementQueue.takeFirst(); 670 } 671 672 SQLTransactionState SQLTransactionBackend::runCurrentStatementAndGetNextState() 673 { 674 if (!m_currentStatementBackend) { 675 // No more statements to run. So move on to the next state. 676 return SQLTransactionState::PostflightAndCommit; 677 } 678 679 m_database->resetAuthorizer(); 680 681 if (m_hasVersionMismatch) 682 m_currentStatementBackend->setVersionMismatchedError(Database::from(m_database.get())); 683 684 if (m_currentStatementBackend->execute(m_database.get())) { 685 if (m_database->lastActionChangedDatabase()) { 686 // Flag this transaction as having changed the database for later delegate notification 687 m_modifiedDatabase = true; 688 } 689 690 if (m_currentStatementBackend->hasStatementCallback()) { 691 return SQLTransactionState::DeliverStatementCallback; 692 } 693 694 // If we get here, then the statement doesn't have a callback to invoke. 695 // We can move on to the next statement. Hence, stay in this state. 696 return SQLTransactionState::RunStatements; 697 } 698 699 if (m_currentStatementBackend->lastExecutionFailedDueToQuota()) { 700 return SQLTransactionState::DeliverQuotaIncreaseCallback; 701 } 702 703 return nextStateForCurrentStatementError(); 704 } 705 706 SQLTransactionState SQLTransactionBackend::nextStateForCurrentStatementError() 707 { 708 // Spec 4.3.2.6.6: error - Call the statement's error callback, but if there was no error callback, 709 // or the transaction was rolled back, jump to the transaction error callback 710 if (m_currentStatementBackend->hasStatementErrorCallback() && !m_sqliteTransaction->wasRolledBackBySqlite()) 711 return SQLTransactionState::DeliverStatementCallback; 712 713 m_transactionError = m_currentStatementBackend->sqlError(); 714 if (!m_transactionError) { 715 m_database->reportCommitTransactionResult(1, SQLError::DATABASE_ERR, 0); 716 m_transactionError = SQLError::create(SQLError::DATABASE_ERR, "the statement failed to execute"); 717 } 718 return nextStateForTransactionError(); 719 } 720 721 SQLTransactionState SQLTransactionBackend::postflightAndCommit() 722 { 723 ASSERT(m_lockAcquired); 724 725 // Spec 4.3.2.7: Perform postflight steps, jumping to the error callback if they fail. 726 if (m_wrapper && !m_wrapper->performPostflight(this)) { 727 m_transactionError = m_wrapper->sqlError(); 728 if (!m_transactionError) { 729 m_database->reportCommitTransactionResult(3, SQLError::UNKNOWN_ERR, 0); 730 m_transactionError = SQLError::create(SQLError::UNKNOWN_ERR, "unknown error occurred during transaction postflight"); 731 } 732 return nextStateForTransactionError(); 733 } 734 735 // Spec 4.3.2.7: Commit the transaction, jumping to the error callback if that fails. 736 ASSERT(m_sqliteTransaction); 737 738 m_database->disableAuthorizer(); 739 m_sqliteTransaction->commit(); 740 m_database->enableAuthorizer(); 741 742 // If the commit failed, the transaction will still be marked as "in progress" 743 if (m_sqliteTransaction->inProgress()) { 744 if (m_wrapper) 745 m_wrapper->handleCommitFailedAfterPostflight(this); 746 m_database->reportCommitTransactionResult(4, SQLError::DATABASE_ERR, m_database->sqliteDatabase().lastError()); 747 m_transactionError = SQLError::create(SQLError::DATABASE_ERR, "unable to commit transaction", 748 m_database->sqliteDatabase().lastError(), m_database->sqliteDatabase().lastErrorMsg()); 749 return nextStateForTransactionError(); 750 } 751 752 m_database->reportCommitTransactionResult(0, -1, 0); // OK 753 754 // Vacuum the database if anything was deleted. 755 if (m_database->hadDeletes()) 756 m_database->incrementalVacuumIfNeeded(); 757 758 // The commit was successful. If the transaction modified this database, notify the delegates. 759 if (m_modifiedDatabase) 760 m_database->transactionClient()->didCommitWriteTransaction(database()); 761 762 // Spec 4.3.2.8: Deliver success callback, if there is one. 763 return SQLTransactionState::DeliverSuccessCallback; 764 } 765 766 SQLTransactionState SQLTransactionBackend::cleanupAndTerminate() 767 { 768 ASSERT(m_lockAcquired); 769 770 // Spec 4.3.2.9: End transaction steps. There is no next step. 771 LOG(StorageAPI, "Transaction %p is complete\n", this); 772 ASSERT(!m_database->sqliteDatabase().transactionInProgress()); 773 774 // Phase 5 cleanup. See comment on the SQLTransaction life-cycle above. 775 doCleanup(); 776 m_database->inProgressTransactionCompleted(); 777 return SQLTransactionState::End; 778 } 779 780 SQLTransactionState SQLTransactionBackend::nextStateForTransactionError() 781 { 782 ASSERT(m_transactionError); 783 if (m_hasErrorCallback) 784 return SQLTransactionState::DeliverTransactionErrorCallback; 785 786 // No error callback, so fast-forward to the next state and rollback the 787 // transaction. 788 return SQLTransactionState::CleanupAfterTransactionErrorCallback; 789 } 790 791 SQLTransactionState SQLTransactionBackend::cleanupAfterTransactionErrorCallback() 792 { 793 ASSERT(m_lockAcquired); 794 795 LOG(StorageAPI, "Transaction %p is complete with an error\n", this); 796 m_database->disableAuthorizer(); 797 if (m_sqliteTransaction) { 798 // Spec 4.3.2.10: Rollback the transaction. 799 m_sqliteTransaction->rollback(); 800 801 ASSERT(!m_database->sqliteDatabase().transactionInProgress()); 802 m_sqliteTransaction.clear(); 803 } 804 m_database->enableAuthorizer(); 805 806 ASSERT(!m_database->sqliteDatabase().transactionInProgress()); 807 808 return SQLTransactionState::CleanupAndTerminate; 809 } 810 811 // requestTransitToState() can be called from the frontend. Hence, it should 812 // NOT be modifying SQLTransactionBackend in general. The only safe field to 813 // modify is m_requestedState which is meant for this purpose. 814 void SQLTransactionBackend::requestTransitToState(SQLTransactionState nextState) 815 { 816 LOG(StorageAPI, "Scheduling %s for transaction %p\n", nameForSQLTransactionState(nextState), this); 817 m_requestedState = nextState; 818 ASSERT(m_requestedState != SQLTransactionState::End); 819 m_database->scheduleTransactionStep(this); 820 } 821 822 // This state function is used as a stub function to plug unimplemented states 823 // in the state dispatch table. They are unimplemented because they should 824 // never be reached in the course of correct execution. 825 SQLTransactionState SQLTransactionBackend::unreachableState() 826 { 827 ASSERT_NOT_REACHED(); 828 return SQLTransactionState::End; 829 } 830 831 SQLTransactionState SQLTransactionBackend::sendToFrontendState() 832 { 833 ASSERT(m_nextState != SQLTransactionState::Idle); 834 m_frontend->requestTransitToState(m_nextState); 835 return SQLTransactionState::Idle; 836 } 837 838 } // namespace WebCore 839