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