|
1 /**************************************************************************** |
|
2 ** |
|
3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). |
|
4 ** All rights reserved. |
|
5 ** Contact: Nokia Corporation (qt-info@nokia.com) |
|
6 ** |
|
7 ** This file is part of the QtDeclarative module of the Qt Toolkit. |
|
8 ** |
|
9 ** $QT_BEGIN_LICENSE:LGPL$ |
|
10 ** No Commercial Usage |
|
11 ** This file contains pre-release code and may not be distributed. |
|
12 ** You may use this file in accordance with the terms and conditions |
|
13 ** contained in the Technology Preview License Agreement accompanying |
|
14 ** this package. |
|
15 ** |
|
16 ** GNU Lesser General Public License Usage |
|
17 ** Alternatively, this file may be used under the terms of the GNU Lesser |
|
18 ** General Public License version 2.1 as published by the Free Software |
|
19 ** Foundation and appearing in the file LICENSE.LGPL included in the |
|
20 ** packaging of this file. Please review the following information to |
|
21 ** ensure the GNU Lesser General Public License version 2.1 requirements |
|
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. |
|
23 ** |
|
24 ** In addition, as a special exception, Nokia gives you certain additional |
|
25 ** rights. These rights are described in the Nokia Qt LGPL Exception |
|
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. |
|
27 ** |
|
28 ** If you have questions regarding the use of this file, please contact |
|
29 ** Nokia at qt-info@nokia.com. |
|
30 ** |
|
31 ** |
|
32 ** |
|
33 ** |
|
34 ** |
|
35 ** |
|
36 ** |
|
37 ** |
|
38 ** $QT_END_LICENSE$ |
|
39 ** |
|
40 ****************************************************************************/ |
|
41 |
|
42 #include "private/qdeclarativesqldatabase_p.h" |
|
43 |
|
44 #include "qdeclarativeengine.h" |
|
45 #include "private/qdeclarativeengine_p.h" |
|
46 #include "private/qdeclarativerefcount_p.h" |
|
47 #include "private/qdeclarativeengine_p.h" |
|
48 |
|
49 #include <QtCore/qobject.h> |
|
50 #include <QtScript/qscriptvalue.h> |
|
51 #include <QtScript/qscriptvalueiterator.h> |
|
52 #include <QtScript/qscriptcontext.h> |
|
53 #include <QtScript/qscriptengine.h> |
|
54 #include <QtScript/qscriptclasspropertyiterator.h> |
|
55 #include <QtSql/qsqldatabase.h> |
|
56 #include <QtSql/qsqlquery.h> |
|
57 #include <QtSql/qsqlerror.h> |
|
58 #include <QtSql/qsqlrecord.h> |
|
59 #include <QtCore/qstack.h> |
|
60 #include <QtCore/qcryptographichash.h> |
|
61 #include <QtCore/qsettings.h> |
|
62 #include <QtCore/qdir.h> |
|
63 #include <QtCore/qdebug.h> |
|
64 |
|
65 Q_DECLARE_METATYPE(QSqlDatabase) |
|
66 Q_DECLARE_METATYPE(QSqlQuery) |
|
67 |
|
68 QT_BEGIN_NAMESPACE |
|
69 |
|
70 class QDeclarativeSqlQueryScriptClass: public QScriptClass { |
|
71 public: |
|
72 QDeclarativeSqlQueryScriptClass(QScriptEngine *engine) : QScriptClass(engine) |
|
73 { |
|
74 str_length = engine->toStringHandle(QLatin1String("length")); |
|
75 str_forwardOnly = engine->toStringHandle(QLatin1String("forwardOnly")); // not in HTML5 (an optimization) |
|
76 } |
|
77 |
|
78 QueryFlags queryProperty(const QScriptValue &, |
|
79 const QScriptString &name, |
|
80 QueryFlags flags, uint *) |
|
81 { |
|
82 if (flags & HandlesReadAccess) { |
|
83 if (name == str_length) { |
|
84 return HandlesReadAccess; |
|
85 } else if (name == str_forwardOnly) { |
|
86 return flags; |
|
87 } |
|
88 } |
|
89 if (flags & HandlesWriteAccess) |
|
90 if (name == str_forwardOnly) |
|
91 return flags; |
|
92 return 0; |
|
93 } |
|
94 |
|
95 QScriptValue property(const QScriptValue &object, |
|
96 const QScriptString &name, uint) |
|
97 { |
|
98 QSqlQuery query = qscriptvalue_cast<QSqlQuery>(object.data()); |
|
99 if (name == str_length) { |
|
100 int s = query.size(); |
|
101 if (s<0) { |
|
102 // Inefficient. |
|
103 if (query.last()) { |
|
104 return query.at()+1; |
|
105 } else { |
|
106 return 0; |
|
107 } |
|
108 } else { |
|
109 return s; |
|
110 } |
|
111 } else if (name == str_forwardOnly) { |
|
112 return query.isForwardOnly(); |
|
113 } |
|
114 return engine()->undefinedValue(); |
|
115 } |
|
116 |
|
117 void setProperty(QScriptValue &object, |
|
118 const QScriptString &name, uint, const QScriptValue & value) |
|
119 { |
|
120 if (name == str_forwardOnly) { |
|
121 QSqlQuery query = qscriptvalue_cast<QSqlQuery>(object.data()); |
|
122 query.setForwardOnly(value.toBool()); |
|
123 } |
|
124 } |
|
125 |
|
126 QScriptValue::PropertyFlags propertyFlags(const QScriptValue &/*object*/, const QScriptString &name, uint /*id*/) |
|
127 { |
|
128 if (name == str_length) { |
|
129 return QScriptValue::Undeletable |
|
130 | QScriptValue::SkipInEnumeration; |
|
131 } |
|
132 return QScriptValue::Undeletable; |
|
133 } |
|
134 |
|
135 private: |
|
136 QScriptString str_length; |
|
137 QScriptString str_forwardOnly; |
|
138 }; |
|
139 |
|
140 // If the spec changes to allow iteration, check git history... |
|
141 // class QDeclarativeSqlQueryScriptClassPropertyIterator : public QScriptClassPropertyIterator |
|
142 |
|
143 |
|
144 |
|
145 enum SqlException { |
|
146 UNKNOWN_ERR, |
|
147 DATABASE_ERR, |
|
148 VERSION_ERR, |
|
149 TOO_LARGE_ERR, |
|
150 QUOTA_ERR, |
|
151 SYNTAX_ERR, |
|
152 CONSTRAINT_ERR, |
|
153 TIMEOUT_ERR |
|
154 }; |
|
155 |
|
156 static const char* sqlerror[] = { |
|
157 "UNKNOWN_ERR", |
|
158 "DATABASE_ERR", |
|
159 "VERSION_ERR", |
|
160 "TOO_LARGE_ERR", |
|
161 "QUOTA_ERR", |
|
162 "SYNTAX_ERR", |
|
163 "CONSTRAINT_ERR", |
|
164 "TIMEOUT_ERR", |
|
165 0 |
|
166 }; |
|
167 |
|
168 #define THROW_SQL(error, desc) \ |
|
169 { \ |
|
170 QScriptValue errorValue = context->throwError(desc); \ |
|
171 errorValue.setProperty(QLatin1String("code"), error); \ |
|
172 return errorValue; \ |
|
173 } |
|
174 |
|
175 |
|
176 static QString databaseFile(const QString& connectionName, QScriptEngine *engine) |
|
177 { |
|
178 QDeclarativeScriptEngine *qmlengine = static_cast<QDeclarativeScriptEngine*>(engine); |
|
179 QString basename = qmlengine->offlineStoragePath |
|
180 + QDir::separator() + QLatin1String("Databases") + QDir::separator(); |
|
181 basename += connectionName; |
|
182 return basename; |
|
183 } |
|
184 |
|
185 |
|
186 |
|
187 static QScriptValue qmlsqldatabase_item(QScriptContext *context, QScriptEngine *engine) |
|
188 { |
|
189 QSqlQuery query = qscriptvalue_cast<QSqlQuery>(context->thisObject().data()); |
|
190 int i = context->argument(0).toNumber(); |
|
191 if (query.at() == i || query.seek(i)) { // Qt 4.6 doesn't optimize seek(at()) |
|
192 QSqlRecord r = query.record(); |
|
193 QScriptValue row = engine->newObject(); |
|
194 for (int j=0; j<r.count(); ++j) { |
|
195 row.setProperty(r.fieldName(j), QScriptValue(engine,r.value(j).toString())); |
|
196 } |
|
197 return row; |
|
198 } |
|
199 return engine->undefinedValue(); |
|
200 } |
|
201 |
|
202 static QScriptValue qmlsqldatabase_executeSql_outsidetransaction(QScriptContext *context, QScriptEngine * /*engine*/) |
|
203 { |
|
204 THROW_SQL(DATABASE_ERR,QDeclarativeEngine::tr("executeSql called outside transaction()")); |
|
205 } |
|
206 |
|
207 static QScriptValue qmlsqldatabase_executeSql(QScriptContext *context, QScriptEngine *engine) |
|
208 { |
|
209 QSqlDatabase db = qscriptvalue_cast<QSqlDatabase>(context->thisObject()); |
|
210 QString sql = context->argument(0).toString(); |
|
211 QSqlQuery query(db); |
|
212 bool err = false; |
|
213 |
|
214 QScriptValue result; |
|
215 |
|
216 if (query.prepare(sql)) { |
|
217 if (context->argumentCount() > 1) { |
|
218 QScriptValue values = context->argument(1); |
|
219 if (values.isObject()) { |
|
220 if (values.isArray()) { |
|
221 int size = values.property(QLatin1String("length")).toInt32(); |
|
222 for (int i = 0; i < size; ++i) |
|
223 query.bindValue(i, values.property(i).toVariant()); |
|
224 } else { |
|
225 for (QScriptValueIterator it(values); it.hasNext();) { |
|
226 it.next(); |
|
227 query.bindValue(it.name(),it.value().toVariant()); |
|
228 } |
|
229 } |
|
230 } else { |
|
231 query.bindValue(0,values.toVariant()); |
|
232 } |
|
233 } |
|
234 if (query.exec()) { |
|
235 result = engine->newObject(); |
|
236 QDeclarativeScriptEngine *qmlengine = static_cast<QDeclarativeScriptEngine*>(engine); |
|
237 if (!qmlengine->sqlQueryClass) |
|
238 qmlengine->sqlQueryClass = new QDeclarativeSqlQueryScriptClass(engine); |
|
239 QScriptValue rows = engine->newObject(qmlengine->sqlQueryClass); |
|
240 rows.setData(engine->newVariant(qVariantFromValue(query))); |
|
241 rows.setProperty(QLatin1String("item"), engine->newFunction(qmlsqldatabase_item,1), QScriptValue::SkipInEnumeration); |
|
242 result.setProperty(QLatin1String("rows"),rows); |
|
243 result.setProperty(QLatin1String("rowsAffected"),query.numRowsAffected()); |
|
244 result.setProperty(QLatin1String("insertId"),query.lastInsertId().toString()); |
|
245 } else { |
|
246 err = true; |
|
247 } |
|
248 } else { |
|
249 err = true; |
|
250 } |
|
251 if (err) |
|
252 THROW_SQL(DATABASE_ERR,query.lastError().text()); |
|
253 return result; |
|
254 } |
|
255 |
|
256 static QScriptValue qmlsqldatabase_executeSql_readonly(QScriptContext *context, QScriptEngine *engine) |
|
257 { |
|
258 QString sql = context->argument(0).toString(); |
|
259 if (sql.startsWith(QLatin1String("SELECT"),Qt::CaseInsensitive)) { |
|
260 return qmlsqldatabase_executeSql(context,engine); |
|
261 } else { |
|
262 THROW_SQL(SYNTAX_ERR,QDeclarativeEngine::tr("Read-only Transaction")) |
|
263 } |
|
264 } |
|
265 |
|
266 static QScriptValue qmlsqldatabase_change_version(QScriptContext *context, QScriptEngine *engine) |
|
267 { |
|
268 if (context->argumentCount() < 2) |
|
269 return engine->undefinedValue(); |
|
270 |
|
271 QSqlDatabase db = qscriptvalue_cast<QSqlDatabase>(context->thisObject()); |
|
272 QString from_version = context->argument(0).toString(); |
|
273 QString to_version = context->argument(1).toString(); |
|
274 QScriptValue callback = context->argument(2); |
|
275 |
|
276 QScriptValue instance = engine->newObject(); |
|
277 instance.setProperty(QLatin1String("executeSql"), engine->newFunction(qmlsqldatabase_executeSql,1)); |
|
278 QScriptValue tx = engine->newVariant(instance,qVariantFromValue(db)); |
|
279 |
|
280 QString foundvers = context->thisObject().property(QLatin1String("version")).toString(); |
|
281 if (from_version!=foundvers) { |
|
282 THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("Version mismatch: expected %1, found %2").arg(from_version).arg(foundvers)); |
|
283 return engine->undefinedValue(); |
|
284 } |
|
285 |
|
286 bool ok = true; |
|
287 if (callback.isFunction()) { |
|
288 ok = false; |
|
289 db.transaction(); |
|
290 callback.call(QScriptValue(), QScriptValueList() << tx); |
|
291 if (engine->hasUncaughtException()) { |
|
292 db.rollback(); |
|
293 } else { |
|
294 if (!db.commit()) { |
|
295 db.rollback(); |
|
296 THROW_SQL(UNKNOWN_ERR,QDeclarativeEngine::tr("SQL transaction failed")); |
|
297 } else { |
|
298 ok = true; |
|
299 } |
|
300 } |
|
301 } |
|
302 |
|
303 if (ok) { |
|
304 context->thisObject().setProperty(QLatin1String("version"), to_version, QScriptValue::ReadOnly); |
|
305 QSettings ini(databaseFile(db.connectionName(),engine)+QLatin1String(".ini"),QSettings::IniFormat); |
|
306 ini.setValue(QLatin1String("Version"), to_version); |
|
307 } |
|
308 |
|
309 return engine->undefinedValue(); |
|
310 } |
|
311 |
|
312 static QScriptValue qmlsqldatabase_transaction_shared(QScriptContext *context, QScriptEngine *engine, bool readOnly) |
|
313 { |
|
314 QSqlDatabase db = qscriptvalue_cast<QSqlDatabase>(context->thisObject()); |
|
315 QScriptValue callback = context->argument(0); |
|
316 if (!callback.isFunction()) |
|
317 THROW_SQL(UNKNOWN_ERR,QDeclarativeEngine::tr("transaction: missing callback")); |
|
318 |
|
319 QScriptValue instance = engine->newObject(); |
|
320 instance.setProperty(QLatin1String("executeSql"), |
|
321 engine->newFunction(readOnly ? qmlsqldatabase_executeSql_readonly : qmlsqldatabase_executeSql,1)); |
|
322 QScriptValue tx = engine->newVariant(instance,qVariantFromValue(db)); |
|
323 |
|
324 db.transaction(); |
|
325 callback.call(QScriptValue(), QScriptValueList() << tx); |
|
326 instance.setProperty(QLatin1String("executeSql"), |
|
327 engine->newFunction(qmlsqldatabase_executeSql_outsidetransaction)); |
|
328 if (engine->hasUncaughtException()) { |
|
329 db.rollback(); |
|
330 } else { |
|
331 if (!db.commit()) |
|
332 db.rollback(); |
|
333 } |
|
334 return engine->undefinedValue(); |
|
335 } |
|
336 |
|
337 static QScriptValue qmlsqldatabase_transaction(QScriptContext *context, QScriptEngine *engine) |
|
338 { |
|
339 return qmlsqldatabase_transaction_shared(context,engine,false); |
|
340 } |
|
341 static QScriptValue qmlsqldatabase_read_transaction(QScriptContext *context, QScriptEngine *engine) |
|
342 { |
|
343 return qmlsqldatabase_transaction_shared(context,engine,true); |
|
344 } |
|
345 |
|
346 /* |
|
347 Currently documented in doc/src/declarastive/globalobject.qdoc |
|
348 */ |
|
349 static QScriptValue qmlsqldatabase_open_sync(QScriptContext *context, QScriptEngine *engine) |
|
350 { |
|
351 QSqlDatabase database; |
|
352 |
|
353 QString dbname = context->argument(0).toString(); |
|
354 QString dbversion = context->argument(1).toString(); |
|
355 QString dbdescription = context->argument(2).toString(); |
|
356 int dbestimatedsize = context->argument(3).toNumber(); |
|
357 QScriptValue dbcreationCallback = context->argument(4); |
|
358 |
|
359 QCryptographicHash md5(QCryptographicHash::Md5); |
|
360 md5.addData(dbname.toUtf8()); |
|
361 QString dbid(QLatin1String(md5.result().toHex())); |
|
362 |
|
363 QString basename = databaseFile(dbid,engine); |
|
364 bool created = false; |
|
365 QString version = dbversion; |
|
366 |
|
367 { |
|
368 QSettings ini(basename+QLatin1String(".ini"),QSettings::IniFormat); |
|
369 |
|
370 if (QSqlDatabase::connectionNames().contains(dbid)) { |
|
371 database = QSqlDatabase::database(dbid); |
|
372 version = ini.value(QLatin1String("Version")).toString(); |
|
373 if (version != dbversion && !dbversion.isEmpty() && !version.isEmpty()) |
|
374 THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("SQL: database version mismatch")); |
|
375 } else { |
|
376 created = !QFile::exists(basename+QLatin1String(".sqlite")); |
|
377 database = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), dbid); |
|
378 QDir().mkpath(basename); |
|
379 if (created) { |
|
380 ini.setValue(QLatin1String("Name"), dbname); |
|
381 if (dbcreationCallback.isFunction()) |
|
382 version = QString(); |
|
383 ini.setValue(QLatin1String("Version"), version); |
|
384 ini.setValue(QLatin1String("Description"), dbdescription); |
|
385 ini.setValue(QLatin1String("EstimatedSize"), dbestimatedsize); |
|
386 ini.setValue(QLatin1String("Driver"), QLatin1String("QSQLITE")); |
|
387 } else { |
|
388 if (!dbversion.isEmpty() && ini.value(QLatin1String("Version")) != dbversion) { |
|
389 // Incompatible |
|
390 THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("SQL: database version mismatch")); |
|
391 } |
|
392 version = ini.value(QLatin1String("Version")).toString(); |
|
393 } |
|
394 database.setDatabaseName(basename+QLatin1String(".sqlite")); |
|
395 } |
|
396 if (!database.isOpen()) |
|
397 database.open(); |
|
398 } |
|
399 |
|
400 QScriptValue instance = engine->newObject(); |
|
401 instance.setProperty(QLatin1String("transaction"), engine->newFunction(qmlsqldatabase_transaction,1)); |
|
402 instance.setProperty(QLatin1String("readTransaction"), engine->newFunction(qmlsqldatabase_read_transaction,1)); |
|
403 instance.setProperty(QLatin1String("version"), version, QScriptValue::ReadOnly); |
|
404 instance.setProperty(QLatin1String("changeVersion"), engine->newFunction(qmlsqldatabase_change_version,3)); |
|
405 |
|
406 QScriptValue result = engine->newVariant(instance,qVariantFromValue(database)); |
|
407 |
|
408 if (created && dbcreationCallback.isFunction()) { |
|
409 dbcreationCallback.call(QScriptValue(), QScriptValueList() << result); |
|
410 } |
|
411 |
|
412 return result; |
|
413 } |
|
414 |
|
415 void qt_add_qmlsqldatabase(QScriptEngine *engine) |
|
416 { |
|
417 QScriptValue openDatabase = engine->newFunction(qmlsqldatabase_open_sync, 4); |
|
418 engine->globalObject().setProperty(QLatin1String("openDatabaseSync"), openDatabase); |
|
419 |
|
420 QScriptValue sqlExceptionPrototype = engine->newObject(); |
|
421 for (int i=0; sqlerror[i]; ++i) |
|
422 sqlExceptionPrototype.setProperty(QLatin1String(sqlerror[i]), |
|
423 i,QScriptValue::ReadOnly | QScriptValue::Undeletable | QScriptValue::SkipInEnumeration); |
|
424 |
|
425 engine->globalObject().setProperty(QLatin1String("SQLException"), sqlExceptionPrototype); |
|
426 } |
|
427 |
|
428 /* |
|
429 HTML5 "spec" says "rs.rows[n]", but WebKit only impelments "rs.rows.item(n)". We do both (and property iterator). |
|
430 We add a "forwardOnly" property that stops Qt caching results (code promises to only go forward |
|
431 through the data. |
|
432 */ |
|
433 |
|
434 QT_END_NAMESPACE |