2 * Copyright (C) 2007, 2013 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
29 #include "modules/webdatabase/SQLStatementBackend.h"
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"
40 // The Life-Cycle of a SQLStatement i.e. Who's keeping the SQLStatement alive?
41 // ==========================================================================
42 // The RefPtr chain goes something like this:
44 // At birth (in SQLTransactionBackend::executeSQL()):
45 // =================================================
46 // SQLTransactionBackend // Deque<RefPtr<SQLStatementBackend> > m_statementQueue points to ...
47 // --> SQLStatementBackend // OwnPtr<SQLStatement> m_frontend points to ...
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 ...
56 // Then we execute the statement in SQLTransactionBackend::runCurrentStatementAndGetNextState().
57 // And we callback to the script in SQLTransaction::deliverStatementCallback() if
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.
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.
69 // Note: unlike with SQLTransaction, there is no JS representation of SQLStatement.
70 // Hence, there is no GC dependency at play here.
74 PassRefPtr<SQLStatementBackend> SQLStatementBackend::create(PassOwnPtr<AbstractSQLStatement> frontend,
75 const String& statement, const Vector<SQLValue>& arguments, int permissions)
77 return adoptRef(new SQLStatementBackend(frontend, statement, arguments, permissions));
80 SQLStatementBackend::SQLStatementBackend(PassOwnPtr<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_permissions(permissions)
89 m_frontend->setBackend(this);
92 AbstractSQLStatement* SQLStatementBackend::frontend()
94 return m_frontend.get();
97 PassRefPtr<SQLError> SQLStatementBackend::sqlError() const
102 PassRefPtr<SQLResultSet> SQLStatementBackend::sqlResultSet() const
107 bool SQLStatementBackend::execute(DatabaseBackend* db)
109 ASSERT(!m_resultSet);
111 // If we're re-running this statement after a quota violation, we need to clear that error now
112 clearFailureDueToQuota();
114 // This transaction might have been marked bad while it was being set up on the main thread,
115 // so if there is still an error, return false.
119 db->setAuthorizerPermissions(m_permissions);
121 SQLiteDatabase* database = &db->sqliteDatabase();
123 SQLiteStatement statement(*database, m_statement);
124 int result = statement.prepare();
126 if (result != SQLResultOk) {
127 WTF_LOG(StorageAPI, "Unable to verify correctness of statement %s - error %i (%s)", m_statement.ascii().data(), result, database->lastErrorMsg());
128 if (result == SQLResultInterrupt)
129 m_error = SQLError::create(SQLError::DATABASE_ERR, "could not prepare statement", result, "interrupted");
131 m_error = SQLError::create(SQLError::SYNTAX_ERR, "could not prepare statement", result, database->lastErrorMsg());
132 db->reportExecuteStatementResult(1, m_error->code(), result);
136 // FIXME: If the statement uses the ?### syntax supported by sqlite, the bind parameter count is very likely off from the number of question marks.
137 // If this is the case, they might be trying to do something fishy or malicious
138 if (statement.bindParameterCount() != m_arguments.size()) {
139 WTF_LOG(StorageAPI, "Bind parameter count doesn't match number of question marks");
140 m_error = SQLError::create(db->isInterrupted() ? SQLError::DATABASE_ERR : SQLError::SYNTAX_ERR, "number of '?'s in statement string does not match argument count");
141 db->reportExecuteStatementResult(2, m_error->code(), 0);
145 for (unsigned i = 0; i < m_arguments.size(); ++i) {
146 result = statement.bindValue(i + 1, m_arguments[i]);
147 if (result == SQLResultFull) {
148 setFailureDueToQuota(db);
152 if (result != SQLResultOk) {
153 WTF_LOG(StorageAPI, "Failed to bind value index %i to statement for query '%s'", i + 1, m_statement.ascii().data());
154 db->reportExecuteStatementResult(3, SQLError::DATABASE_ERR, result);
155 m_error = SQLError::create(SQLError::DATABASE_ERR, "could not bind value", result, database->lastErrorMsg());
160 RefPtr<SQLResultSet> resultSet = SQLResultSet::create();
162 // Step so we can fetch the column names.
163 result = statement.step();
164 if (result == SQLResultRow) {
165 int columnCount = statement.columnCount();
166 SQLResultSetRowList* rows = resultSet->rows();
168 for (int i = 0; i < columnCount; i++)
169 rows->addColumn(statement.getColumnName(i));
172 for (int i = 0; i < columnCount; i++)
173 rows->addResult(statement.getColumnValue(i));
175 result = statement.step();
176 } while (result == SQLResultRow);
178 if (result != SQLResultDone) {
179 db->reportExecuteStatementResult(4, SQLError::DATABASE_ERR, result);
180 m_error = SQLError::create(SQLError::DATABASE_ERR, "could not iterate results", result, database->lastErrorMsg());
183 } else if (result == SQLResultDone) {
184 // Didn't find anything, or was an insert
185 if (db->lastActionWasInsert())
186 resultSet->setInsertId(database->lastInsertRowID());
187 } else if (result == SQLResultFull) {
188 // Return the Quota error - the delegate will be asked for more space and this statement might be re-run
189 setFailureDueToQuota(db);
191 } else if (result == SQLResultConstraint) {
192 db->reportExecuteStatementResult(6, SQLError::CONSTRAINT_ERR, result);
193 m_error = SQLError::create(SQLError::CONSTRAINT_ERR, "could not execute statement due to a constaint failure", result, database->lastErrorMsg());
196 db->reportExecuteStatementResult(5, SQLError::DATABASE_ERR, result);
197 m_error = SQLError::create(SQLError::DATABASE_ERR, "could not execute statement", result, database->lastErrorMsg());
201 // FIXME: If the spec allows triggers, and we want to be "accurate" in a different way, we'd use
202 // sqlite3_total_changes() here instead of sqlite3_changed, because that includes rows modified from within a trigger
203 // For now, this seems sufficient
204 resultSet->setRowsAffected(database->lastChanges());
206 m_resultSet = resultSet;
207 db->reportExecuteStatementResult(0, -1, 0); // OK
211 void SQLStatementBackend::setVersionMismatchedError(DatabaseBackend* database)
213 ASSERT(!m_error && !m_resultSet);
214 database->reportExecuteStatementResult(7, SQLError::VERSION_ERR, 0);
215 m_error = SQLError::create(SQLError::VERSION_ERR, "current version of the database and `oldVersion` argument do not match");
218 void SQLStatementBackend::setFailureDueToQuota(DatabaseBackend* database)
220 ASSERT(!m_error && !m_resultSet);
221 database->reportExecuteStatementResult(8, SQLError::QUOTA_ERR, 0);
222 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");
225 void SQLStatementBackend::clearFailureDueToQuota()
227 if (lastExecutionFailedDueToQuota())
231 bool SQLStatementBackend::lastExecutionFailedDueToQuota() const
233 return m_error && m_error->code() == SQLError::QUOTA_ERR;
236 } // namespace WebCore