Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / modules / webdatabase / SQLStatementBackend.cpp
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
74 PassRefPtr<SQLStatementBackend> SQLStatementBackend::create(PassOwnPtr<AbstractSQLStatement> frontend,
75     const String& statement, const Vector<SQLValue>& arguments, int permissions)
76 {
77     return adoptRef(new SQLStatementBackend(frontend, statement, arguments, permissions));
78 }
79
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)
88 {
89     m_frontend->setBackend(this);
90 }
91
92 AbstractSQLStatement* SQLStatementBackend::frontend()
93 {
94     return m_frontend.get();
95 }
96
97 PassRefPtr<SQLError> SQLStatementBackend::sqlError() const
98 {
99     return m_error;
100 }
101
102 PassRefPtr<SQLResultSet> SQLStatementBackend::sqlResultSet() const
103 {
104     return m_resultSet;
105 }
106
107 bool SQLStatementBackend::execute(DatabaseBackend* db)
108 {
109     ASSERT(!m_resultSet);
110
111     // If we're re-running this statement after a quota violation, we need to clear that error now
112     clearFailureDueToQuota();
113
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.
116     if (m_error)
117         return false;
118
119     db->setAuthorizerPermissions(m_permissions);
120
121     SQLiteDatabase* database = &db->sqliteDatabase();
122
123     SQLiteStatement statement(*database, m_statement);
124     int result = statement.prepare();
125
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");
130         else
131             m_error = SQLError::create(SQLError::SYNTAX_ERR, "could not prepare statement", result, database->lastErrorMsg());
132         db->reportExecuteStatementResult(1, m_error->code(), result);
133         return false;
134     }
135
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);
142         return false;
143     }
144
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);
149             return false;
150         }
151
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());
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             db->reportExecuteStatementResult(4, SQLError::DATABASE_ERR, result);
180             m_error = SQLError::create(SQLError::DATABASE_ERR, "could not iterate results", result, database->lastErrorMsg());
181             return false;
182         }
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);
190         return false;
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());
194         return false;
195     } else {
196         db->reportExecuteStatementResult(5, SQLError::DATABASE_ERR, result);
197         m_error = SQLError::create(SQLError::DATABASE_ERR, "could not execute statement", result, database->lastErrorMsg());
198         return false;
199     }
200
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());
205
206     m_resultSet = resultSet;
207     db->reportExecuteStatementResult(0, -1, 0); // OK
208     return true;
209 }
210
211 void SQLStatementBackend::setVersionMismatchedError(DatabaseBackend* database)
212 {
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");
216 }
217
218 void SQLStatementBackend::setFailureDueToQuota(DatabaseBackend* database)
219 {
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");
223 }
224
225 void SQLStatementBackend::clearFailureDueToQuota()
226 {
227     if (lastExecutionFailedDueToQuota())
228         m_error = 0;
229 }
230
231 bool SQLStatementBackend::lastExecutionFailedDueToQuota() const
232 {
233     return m_error && m_error->code() == SQLError::QUOTA_ERR;
234 }
235
236 } // namespace WebCore