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 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 "SQLStatementBackend.h"
31 #if ENABLE(SQL_DATABASE)
33 #include "AbstractSQLStatement.h"
34 #include "DatabaseBackend.h"
37 #include "SQLResultSet.h"
39 #include "SQLiteDatabase.h"
40 #include "SQLiteStatement.h"
41 #include <wtf/text/CString.h>
44 // The Life-Cycle of a SQLStatement i.e. Who's keeping the SQLStatement alive?
45 // ==========================================================================
46 // The RefPtr chain goes something like this:
48 // At birth (in SQLTransactionBackend::executeSQL()):
49 // =================================================
50 // SQLTransactionBackend // Deque<RefPtr<SQLStatementBackend>> m_statementQueue points to ...
51 // --> SQLStatementBackend // std::unique_ptr<SQLStatement> m_frontend points to ...
54 // After grabbing the statement for execution (in SQLTransactionBackend::getNextStatement()):
55 // =========================================================================================
56 // SQLTransactionBackend // RefPtr<SQLStatementBackend> m_currentStatementBackend points to ...
57 // --> SQLStatementBackend // std::unique_ptr<SQLStatement> m_frontend points to ...
60 // Then we execute the statement in SQLTransactionBackend::runCurrentStatementAndGetNextState().
61 // And we callback to the script in SQLTransaction::deliverStatementCallback() if
63 // - Inside SQLTransaction::deliverStatementCallback(), we operate on a raw SQLStatement*.
64 // This pointer is valid because it is owned by SQLTransactionBackend's
65 // SQLTransactionBackend::m_currentStatementBackend.
67 // After we're done executing the statement (in SQLTransactionBackend::getNextStatement()):
68 // =======================================================================================
69 // When we're done executing, we'll grab the next statement. But before we
70 // do that, getNextStatement() nullify SQLTransactionBackend::m_currentStatementBackend.
71 // This will trigger the deletion of the SQLStatementBackend and SQLStatement.
73 // Note: unlike with SQLTransaction, there is no JS representation of SQLStatement.
74 // Hence, there is no GC dependency at play here.
78 PassRefPtr<SQLStatementBackend> SQLStatementBackend::create(std::unique_ptr<AbstractSQLStatement> frontend,
79 const String& statement, const Vector<SQLValue>& arguments, int permissions)
81 return adoptRef(new SQLStatementBackend(WTF::move(frontend), statement, arguments, permissions));
84 SQLStatementBackend::SQLStatementBackend(std::unique_ptr<AbstractSQLStatement> frontend,
85 const String& statement, const Vector<SQLValue>& arguments, int permissions)
86 : m_frontend(WTF::move(frontend))
87 , m_statement(statement.isolatedCopy())
88 , m_arguments(arguments)
89 , m_hasCallback(m_frontend->hasCallback())
90 , m_hasErrorCallback(m_frontend->hasErrorCallback())
91 , m_permissions(permissions)
93 m_frontend->setBackend(this);
96 SQLStatementBackend::~SQLStatementBackend()
100 AbstractSQLStatement* SQLStatementBackend::frontend()
102 return m_frontend.get();
105 PassRefPtr<SQLError> SQLStatementBackend::sqlError() const
110 PassRefPtr<SQLResultSet> SQLStatementBackend::sqlResultSet() const
115 bool SQLStatementBackend::execute(DatabaseBackend* db)
117 ASSERT(!m_resultSet);
119 // If we're re-running this statement after a quota violation, we need to clear that error now
120 clearFailureDueToQuota();
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.
127 db->setAuthorizerPermissions(m_permissions);
129 SQLiteDatabase* database = &db->sqliteDatabase();
131 SQLiteStatement statement(*database, m_statement);
132 int result = statement.prepare();
134 if (result != SQLResultOk) {
135 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 = SQLError::create(SQLError::DATABASE_ERR, "could not prepare statement", result, "interrupted");
139 m_error = SQLError::create(SQLError::SYNTAX_ERR, "could not prepare statement", result, database->lastErrorMsg());
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 LOG(StorageAPI, "Bind parameter count doesn't match number of question marks");
147 m_error = SQLError::create(db->isInterrupted() ? SQLError::DATABASE_ERR : SQLError::SYNTAX_ERR, "number of '?'s in statement string does not match argument count");
151 for (unsigned i = 0; i < m_arguments.size(); ++i) {
152 result = statement.bindValue(i + 1, m_arguments[i]);
153 if (result == SQLResultFull) {
154 setFailureDueToQuota();
158 if (result != SQLResultOk) {
159 LOG(StorageAPI, "Failed to bind value index %i to statement for query '%s'", i + 1, m_statement.ascii().data());
160 m_error = SQLError::create(SQLError::DATABASE_ERR, "could not bind value", result, database->lastErrorMsg());
165 RefPtr<SQLResultSet> resultSet = SQLResultSet::create();
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 = resultSet->rows();
173 for (int i = 0; i < columnCount; i++)
174 rows->addColumn(statement.getColumnName(i));
177 for (int i = 0; i < columnCount; i++)
178 rows->addResult(statement.getColumnValue(i));
180 result = statement.step();
181 } while (result == SQLResultRow);
183 if (result != SQLResultDone) {
184 m_error = SQLError::create(SQLError::DATABASE_ERR, "could not iterate results", result, database->lastErrorMsg());
187 } else if (result == SQLResultDone) {
188 // Didn't find anything, or was an insert
189 if (db->lastActionWasInsert())
190 resultSet->setInsertId(database->lastInsertRowID());
191 } else if (result == SQLResultFull) {
192 // Return the Quota error - the delegate will be asked for more space and this statement might be re-run
193 setFailureDueToQuota();
195 } else if (result == SQLResultConstraint) {
196 m_error = SQLError::create(SQLError::CONSTRAINT_ERR, "could not execute statement due to a constaint failure", result, database->lastErrorMsg());
199 m_error = SQLError::create(SQLError::DATABASE_ERR, "could not execute statement", result, database->lastErrorMsg());
203 // FIXME: If the spec allows triggers, and we want to be "accurate" in a different way, we'd use
204 // sqlite3_total_changes() here instead of sqlite3_changed, because that includes rows modified from within a trigger
205 // For now, this seems sufficient
206 resultSet->setRowsAffected(database->lastChanges());
208 m_resultSet = resultSet;
212 void SQLStatementBackend::setDatabaseDeletedError()
214 ASSERT(!m_error && !m_resultSet);
215 m_error = SQLError::create(SQLError::UNKNOWN_ERR, "unable to execute statement, because the user deleted the database");
218 void SQLStatementBackend::setVersionMismatchedError()
220 ASSERT(!m_error && !m_resultSet);
221 m_error = SQLError::create(SQLError::VERSION_ERR, "current version of the database and `oldVersion` argument do not match");
224 void SQLStatementBackend::setFailureDueToQuota()
226 ASSERT(!m_error && !m_resultSet);
227 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");
230 void SQLStatementBackend::clearFailureDueToQuota()
232 if (lastExecutionFailedDueToQuota())
236 bool SQLStatementBackend::lastExecutionFailedDueToQuota() const
238 return m_error && m_error->code() == SQLError::QUOTA_ERR;
241 } // namespace WebCore
243 #endif // ENABLE(SQL_DATABASE)