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