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 "platform/Logging.h"
32 #include "modules/webdatabase/sqlite/SQLiteDatabase.h"
33 #include "modules/webdatabase/sqlite/SQLiteStatement.h"
34 #include "modules/webdatabase/AbstractSQLStatement.h"
35 #include "modules/webdatabase/DatabaseBackend.h"
36 #include "modules/webdatabase/SQLError.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 WebCore {
73
create(PassOwnPtrWillBeRawPtr<AbstractSQLStatement> frontend,const String & statement,const Vector<SQLValue> & arguments,int permissions)74 PassRefPtrWillBeRawPtr<SQLStatementBackend> SQLStatementBackend::create(PassOwnPtrWillBeRawPtr<AbstractSQLStatement> frontend,
75 const String& statement, const Vector<SQLValue>& arguments, int permissions)
76 {
77 return adoptRefWillBeNoop(new SQLStatementBackend(frontend, statement, arguments, permissions));
78 }
79
SQLStatementBackend(PassOwnPtrWillBeRawPtr<AbstractSQLStatement> frontend,const String & statement,const Vector<SQLValue> & arguments,int permissions)80 SQLStatementBackend::SQLStatementBackend(PassOwnPtrWillBeRawPtr<AbstractSQLStatement> 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
trace(Visitor * visitor)93 void SQLStatementBackend::trace(Visitor* visitor)
94 {
95 visitor->trace(m_frontend);
96 visitor->trace(m_resultSet);
97 AbstractSQLStatementBackend::trace(visitor);
98 }
99
frontend()100 AbstractSQLStatement* SQLStatementBackend::frontend()
101 {
102 return m_frontend.get();
103 }
104
sqlError() const105 SQLErrorData* SQLStatementBackend::sqlError() const
106 {
107 return m_error.get();
108 }
109
sqlResultSet() const110 SQLResultSet* SQLStatementBackend::sqlResultSet() const
111 {
112 return m_resultSet->isValid() ? m_resultSet.get() : 0;
113 }
114
execute(DatabaseBackend * db)115 bool SQLStatementBackend::execute(DatabaseBackend* db)
116 {
117 ASSERT(!m_resultSet->isValid());
118
119 // If we're re-running this statement after a quota violation, we need to clear that error now
120 clearFailureDueToQuota();
121
122 // This transaction might have been marked bad while it was being set up on the main thread,
123 // so if there is still an error, return false.
124 if (m_error)
125 return false;
126
127 db->setAuthorizerPermissions(m_permissions);
128
129 SQLiteDatabase* database = &db->sqliteDatabase();
130
131 SQLiteStatement statement(*database, m_statement);
132 int result = statement.prepare();
133
134 if (result != SQLResultOk) {
135 WTF_LOG(StorageAPI, "Unable to verify correctness of statement %s - error %i (%s)", m_statement.ascii().data(), result, database->lastErrorMsg());
136 if (result == SQLResultInterrupt)
137 m_error = SQLErrorData::create(SQLError::DATABASE_ERR, "could not prepare statement", result, "interrupted");
138 else
139 m_error = SQLErrorData::create(SQLError::SYNTAX_ERR, "could not prepare statement", result, database->lastErrorMsg());
140 db->reportExecuteStatementResult(1, m_error->code(), result);
141 return false;
142 }
143
144 // FIXME: If the statement uses the ?### syntax supported by sqlite, the bind parameter count is very likely off from the number of question marks.
145 // If this is the case, they might be trying to do something fishy or malicious
146 if (statement.bindParameterCount() != m_arguments.size()) {
147 WTF_LOG(StorageAPI, "Bind parameter count doesn't match number of question marks");
148 m_error = SQLErrorData::create(db->isInterrupted() ? SQLError::DATABASE_ERR : SQLError::SYNTAX_ERR, "number of '?'s in statement string does not match argument count");
149 db->reportExecuteStatementResult(2, m_error->code(), 0);
150 return false;
151 }
152
153 for (unsigned i = 0; i < m_arguments.size(); ++i) {
154 result = statement.bindValue(i + 1, m_arguments[i]);
155 if (result == SQLResultFull) {
156 setFailureDueToQuota(db);
157 return false;
158 }
159
160 if (result != SQLResultOk) {
161 WTF_LOG(StorageAPI, "Failed to bind value index %i to statement for query '%s'", i + 1, m_statement.ascii().data());
162 db->reportExecuteStatementResult(3, SQLError::DATABASE_ERR, result);
163 m_error = SQLErrorData::create(SQLError::DATABASE_ERR, "could not bind value", result, database->lastErrorMsg());
164 return false;
165 }
166 }
167
168 // Step so we can fetch the column names.
169 result = statement.step();
170 if (result == SQLResultRow) {
171 int columnCount = statement.columnCount();
172 SQLResultSetRowList* rows = m_resultSet->rows();
173
174 for (int i = 0; i < columnCount; i++)
175 rows->addColumn(statement.getColumnName(i));
176
177 do {
178 for (int i = 0; i < columnCount; i++)
179 rows->addResult(statement.getColumnValue(i));
180
181 result = statement.step();
182 } while (result == SQLResultRow);
183
184 if (result != SQLResultDone) {
185 db->reportExecuteStatementResult(4, SQLError::DATABASE_ERR, result);
186 m_error = SQLErrorData::create(SQLError::DATABASE_ERR, "could not iterate results", result, database->lastErrorMsg());
187 return false;
188 }
189 } else if (result == SQLResultDone) {
190 // Didn't find anything, or was an insert
191 if (db->lastActionWasInsert())
192 m_resultSet->setInsertId(database->lastInsertRowID());
193 } else if (result == SQLResultFull) {
194 // Return the Quota error - the delegate will be asked for more space and this statement might be re-run
195 setFailureDueToQuota(db);
196 return false;
197 } else if (result == SQLResultConstraint) {
198 db->reportExecuteStatementResult(6, SQLError::CONSTRAINT_ERR, result);
199 m_error = SQLErrorData::create(SQLError::CONSTRAINT_ERR, "could not execute statement due to a constaint failure", result, database->lastErrorMsg());
200 return false;
201 } else {
202 db->reportExecuteStatementResult(5, SQLError::DATABASE_ERR, result);
203 m_error = SQLErrorData::create(SQLError::DATABASE_ERR, "could not execute statement", result, database->lastErrorMsg());
204 return false;
205 }
206
207 // FIXME: If the spec allows triggers, and we want to be "accurate" in a different way, we'd use
208 // sqlite3_total_changes() here instead of sqlite3_changed, because that includes rows modified from within a trigger
209 // For now, this seems sufficient
210 m_resultSet->setRowsAffected(database->lastChanges());
211
212 db->reportExecuteStatementResult(0, -1, 0); // OK
213 return true;
214 }
215
setVersionMismatchedError(DatabaseBackend * database)216 void SQLStatementBackend::setVersionMismatchedError(DatabaseBackend* database)
217 {
218 ASSERT(!m_error && !m_resultSet->isValid());
219 database->reportExecuteStatementResult(7, SQLError::VERSION_ERR, 0);
220 m_error = SQLErrorData::create(SQLError::VERSION_ERR, "current version of the database and `oldVersion` argument do not match");
221 }
222
setFailureDueToQuota(DatabaseBackend * database)223 void SQLStatementBackend::setFailureDueToQuota(DatabaseBackend* database)
224 {
225 ASSERT(!m_error && !m_resultSet->isValid());
226 database->reportExecuteStatementResult(8, SQLError::QUOTA_ERR, 0);
227 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");
228 }
229
clearFailureDueToQuota()230 void SQLStatementBackend::clearFailureDueToQuota()
231 {
232 if (lastExecutionFailedDueToQuota())
233 m_error = nullptr;
234 }
235
lastExecutionFailedDueToQuota() const236 bool SQLStatementBackend::lastExecutionFailedDueToQuota() const
237 {
238 return m_error && m_error->code() == SQLError::QUOTA_ERR;
239 }
240
241 } // namespace WebCore
242