1 /* 2 * Copyright (C) 2007, 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 #include "config.h" 29 #include "modules/webdatabase/SQLStatementBackend.h" 30 31 #include "modules/webdatabase/Database.h" 32 #include "modules/webdatabase/SQLError.h" 33 #include "modules/webdatabase/SQLStatement.h" 34 #include "modules/webdatabase/sqlite/SQLiteDatabase.h" 35 #include "modules/webdatabase/sqlite/SQLiteStatement.h" 36 #include "platform/Logging.h" 37 #include "wtf/text/CString.h" 38 39 40 // The Life-Cycle of a SQLStatement i.e. Who's keeping the SQLStatement alive? 41 // ========================================================================== 42 // The RefPtr chain goes something like this: 43 // 44 // At birth (in SQLTransactionBackend::executeSQL()): 45 // ================================================= 46 // SQLTransactionBackend // Deque<RefPtr<SQLStatementBackend> > m_statementQueue points to ... 47 // --> SQLStatementBackend // OwnPtr<SQLStatement> m_frontend points to ... 48 // --> SQLStatement 49 // 50 // After grabbing the statement for execution (in SQLTransactionBackend::getNextStatement()): 51 // ========================================================================================= 52 // SQLTransactionBackend // RefPtr<SQLStatementBackend> m_currentStatementBackend points to ... 53 // --> SQLStatementBackend // OwnPtr<SQLStatement> m_frontend points to ... 54 // --> SQLStatement 55 // 56 // Then we execute the statement in SQLTransactionBackend::runCurrentStatementAndGetNextState(). 57 // And we callback to the script in SQLTransaction::deliverStatementCallback() if 58 // necessary. 59 // - Inside SQLTransaction::deliverStatementCallback(), we operate on a raw SQLStatement*. 60 // This pointer is valid because it is owned by SQLTransactionBackend's 61 // SQLTransactionBackend::m_currentStatementBackend. 62 // 63 // After we're done executing the statement (in SQLTransactionBackend::getNextStatement()): 64 // ======================================================================================= 65 // When we're done executing, we'll grab the next statement. But before we 66 // do that, getNextStatement() nullify SQLTransactionBackend::m_currentStatementBackend. 67 // This will trigger the deletion of the SQLStatementBackend and SQLStatement. 68 // 69 // Note: unlike with SQLTransaction, there is no JS representation of SQLStatement. 70 // Hence, there is no GC dependency at play here. 71 72 namespace blink { 73 74 PassRefPtrWillBeRawPtr<SQLStatementBackend> SQLStatementBackend::create(PassOwnPtrWillBeRawPtr<SQLStatement> frontend, 75 const String& statement, const Vector<SQLValue>& arguments, int permissions) 76 { 77 return adoptRefWillBeNoop(new SQLStatementBackend(frontend, statement, arguments, permissions)); 78 } 79 80 SQLStatementBackend::SQLStatementBackend(PassOwnPtrWillBeRawPtr<SQLStatement> frontend, 81 const String& statement, const Vector<SQLValue>& arguments, int permissions) 82 : m_frontend(frontend) 83 , m_statement(statement.isolatedCopy()) 84 , m_arguments(arguments) 85 , m_hasCallback(m_frontend->hasCallback()) 86 , m_hasErrorCallback(m_frontend->hasErrorCallback()) 87 , m_resultSet(SQLResultSet::create()) 88 , m_permissions(permissions) 89 { 90 m_frontend->setBackend(this); 91 } 92 93 void SQLStatementBackend::trace(Visitor* visitor) 94 { 95 visitor->trace(m_frontend); 96 visitor->trace(m_resultSet); 97 } 98 99 SQLStatement* SQLStatementBackend::frontend() 100 { 101 return m_frontend.get(); 102 } 103 104 SQLErrorData* SQLStatementBackend::sqlError() const 105 { 106 return m_error.get(); 107 } 108 109 SQLResultSet* SQLStatementBackend::sqlResultSet() const 110 { 111 return m_resultSet->isValid() ? m_resultSet.get() : 0; 112 } 113 114 bool SQLStatementBackend::execute(Database* db) 115 { 116 ASSERT(!m_resultSet->isValid()); 117 118 // If we're re-running this statement after a quota violation, we need to clear that error now 119 clearFailureDueToQuota(); 120 121 // This transaction might have been marked bad while it was being set up on the main thread, 122 // so if there is still an error, return false. 123 if (m_error) 124 return false; 125 126 db->setAuthorizerPermissions(m_permissions); 127 128 SQLiteDatabase* database = &db->sqliteDatabase(); 129 130 SQLiteStatement statement(*database, m_statement); 131 int result = statement.prepare(); 132 133 if (result != SQLResultOk) { 134 WTF_LOG(StorageAPI, "Unable to verify correctness of statement %s - error %i (%s)", m_statement.ascii().data(), result, database->lastErrorMsg()); 135 if (result == SQLResultInterrupt) 136 m_error = SQLErrorData::create(SQLError::DATABASE_ERR, "could not prepare statement", result, "interrupted"); 137 else 138 m_error = SQLErrorData::create(SQLError::SYNTAX_ERR, "could not prepare statement", result, database->lastErrorMsg()); 139 db->reportExecuteStatementResult(1, m_error->code(), result); 140 return false; 141 } 142 143 // FIXME: If the statement uses the ?### syntax supported by sqlite, the bind parameter count is very likely off from the number of question marks. 144 // If this is the case, they might be trying to do something fishy or malicious 145 if (statement.bindParameterCount() != m_arguments.size()) { 146 WTF_LOG(StorageAPI, "Bind parameter count doesn't match number of question marks"); 147 m_error = SQLErrorData::create(SQLError::SYNTAX_ERR, "number of '?'s in statement string does not match argument count"); 148 db->reportExecuteStatementResult(2, m_error->code(), 0); 149 return false; 150 } 151 152 for (unsigned i = 0; i < m_arguments.size(); ++i) { 153 result = statement.bindValue(i + 1, m_arguments[i]); 154 if (result == SQLResultFull) { 155 setFailureDueToQuota(db); 156 return false; 157 } 158 159 if (result != SQLResultOk) { 160 WTF_LOG(StorageAPI, "Failed to bind value index %i to statement for query '%s'", i + 1, m_statement.ascii().data()); 161 db->reportExecuteStatementResult(3, SQLError::DATABASE_ERR, result); 162 m_error = SQLErrorData::create(SQLError::DATABASE_ERR, "could not bind value", result, database->lastErrorMsg()); 163 return false; 164 } 165 } 166 167 // Step so we can fetch the column names. 168 result = statement.step(); 169 if (result == SQLResultRow) { 170 int columnCount = statement.columnCount(); 171 SQLResultSetRowList* rows = m_resultSet->rows(); 172 173 for (int i = 0; i < columnCount; i++) 174 rows->addColumn(statement.getColumnName(i)); 175 176 do { 177 for (int i = 0; i < columnCount; i++) 178 rows->addResult(statement.getColumnValue(i)); 179 180 result = statement.step(); 181 } while (result == SQLResultRow); 182 183 if (result != SQLResultDone) { 184 db->reportExecuteStatementResult(4, SQLError::DATABASE_ERR, result); 185 m_error = SQLErrorData::create(SQLError::DATABASE_ERR, "could not iterate results", result, database->lastErrorMsg()); 186 return false; 187 } 188 } else if (result == SQLResultDone) { 189 // Didn't find anything, or was an insert 190 if (db->lastActionWasInsert()) 191 m_resultSet->setInsertId(database->lastInsertRowID()); 192 } else if (result == SQLResultFull) { 193 // Return the Quota error - the delegate will be asked for more space and this statement might be re-run 194 setFailureDueToQuota(db); 195 return false; 196 } else if (result == SQLResultConstraint) { 197 db->reportExecuteStatementResult(6, SQLError::CONSTRAINT_ERR, result); 198 m_error = SQLErrorData::create(SQLError::CONSTRAINT_ERR, "could not execute statement due to a constaint failure", result, database->lastErrorMsg()); 199 return false; 200 } else { 201 db->reportExecuteStatementResult(5, SQLError::DATABASE_ERR, result); 202 m_error = SQLErrorData::create(SQLError::DATABASE_ERR, "could not execute statement", result, database->lastErrorMsg()); 203 return false; 204 } 205 206 // FIXME: If the spec allows triggers, and we want to be "accurate" in a different way, we'd use 207 // sqlite3_total_changes() here instead of sqlite3_changed, because that includes rows modified from within a trigger 208 // For now, this seems sufficient 209 m_resultSet->setRowsAffected(database->lastChanges()); 210 211 db->reportExecuteStatementResult(0, -1, 0); // OK 212 return true; 213 } 214 215 void SQLStatementBackend::setVersionMismatchedError(Database* database) 216 { 217 ASSERT(!m_error && !m_resultSet->isValid()); 218 database->reportExecuteStatementResult(7, SQLError::VERSION_ERR, 0); 219 m_error = SQLErrorData::create(SQLError::VERSION_ERR, "current version of the database and `oldVersion` argument do not match"); 220 } 221 222 void SQLStatementBackend::setFailureDueToQuota(Database* database) 223 { 224 ASSERT(!m_error && !m_resultSet->isValid()); 225 database->reportExecuteStatementResult(8, SQLError::QUOTA_ERR, 0); 226 m_error = SQLErrorData::create(SQLError::QUOTA_ERR, "there was not enough remaining storage space, or the storage quota was reached and the user declined to allow more space"); 227 } 228 229 void SQLStatementBackend::clearFailureDueToQuota() 230 { 231 if (lastExecutionFailedDueToQuota()) 232 m_error = nullptr; 233 } 234 235 bool SQLStatementBackend::lastExecutionFailedDueToQuota() const 236 { 237 return m_error && m_error->code() == SQLError::QUOTA_ERR; 238 } 239 240 } // namespace blink 241