diff options
author | Denis Dzyubenko <denis.dzyubenko@nokia.com> | 2012-05-08 09:00:58 -0700 |
---|---|---|
committer | The Qt Project <gerrit-noreply@qt-project.org> | 2012-10-11 18:26:00 +0200 |
commit | e96eafb2d095553e4cccd2927c0a462d8b8b8d59 (patch) | |
tree | be1a41ef7bcb979d7051ed2c76e1910a49a6cdd0 | |
parent | c29da8f42556856cb7dc8538fc505b9426e0f69e (diff) |
Removed old deprecated c++ api.
This also removed old-style qml api that was using the old c++ api internally.
Change-Id: Iee809bfacb4efeb31e625156420542247354dff7
Reviewed-by: Jamey Hicks <jamey.hicks@nokia.com>
43 files changed, 5 insertions, 7685 deletions
diff --git a/src/clientcompat/clientcompat.pro b/src/clientcompat/clientcompat.pro deleted file mode 100644 index dc00336..0000000 --- a/src/clientcompat/clientcompat.pro +++ /dev/null @@ -1,35 +0,0 @@ -MODULE = jsondbcompat -TARGET = QtJsonDbCompat -VERSION = 1.0.0 - -QT = core -QT_FOR_PRIVATE = network -CONFIG += internal_module - -load(qt_module) - -include(../jsonstream/jsonstream.pri) - -INCLUDEPATH += $$PWD/../common - -HEADERS += \ - jsondb-error.h \ - jsondb-client.h \ - jsondb-object.h \ - jsondb-client_p.h \ - jsondb-connection_p.h \ - jsondb-connection_p_p.h \ - jsondb-query.h \ - jsondb-oneshot_p.h \ - jsondb-strings_p.h \ - jsondb-notification.h - -SOURCES += \ - jsondb-error.cpp \ - jsondb-client.cpp \ - jsondb-object.cpp \ - jsondb-connection.cpp \ - jsondb-query.cpp \ - jsondb-oneshot.cpp \ - jsondb-notification.cpp \ - jsondb-strings.cpp diff --git a/src/clientcompat/jsondb-client.cpp b/src/clientcompat/jsondb-client.cpp deleted file mode 100644 index b3ebcdd..0000000 --- a/src/clientcompat/jsondb-client.cpp +++ /dev/null @@ -1,996 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "jsondb-client.h" -#include "jsondb-client_p.h" -#include "jsondb-strings_p.h" - -#include "jsondb-connection_p.h" - -#include <QEvent> -#include <QUuid> - -/*! - \macro QT_USE_NAMESPACE_JSONDB - \inmodule QtJsonDb - - This macro expands to using jsondb namespace and makes jsondb namespace - visible to C++ source code. - - \code - #include <jsondb-client.h> - QT_USE_NAMESPACE_JSONDB - \endcode - - To declare the class without including the declaration of the class: - - \code - #include <jsondb-global.h> - QT_BEGIN_NAMESPACE_JSONDB - class JsonDbClient; - QT_END_NAMESPACE_JSONDB - QT_USE_NAMESPACE_JSONDB - \endcode -*/ - -/*! - \macro QT_BEGIN_NAMESPACE_JSONDB - \inmodule QtJsonDb - - This macro begins a jsondb namespace. All forward declarations of QtJsonDb classes need to - be wrapped in \c QT_BEGIN_NAMESPACE_JSONDB and \c QT_END_NAMESPACE_JSONDB. - - \sa QT_USE_NAMESPACE_JSONDB, QT_END_NAMESPACE_JSONDB -*/ - -/*! - \macro QT_END_NAMESPACE_JSONDB - \inmodule QtJsonDb - - This macro ends a jsondb namespace. All forward declarations of QtJsonDb classes need to - be wrapped in \c QT_BEGIN_NAMESPACE_JSONDB and \c QT_END_NAMESPACE_JSONDB. - - \sa QT_USE_NAMESPACE_JSONDB, QT_BEGIN_NAMESPACE_JSONDB -*/ - -QT_BEGIN_NAMESPACE_JSONDB - -/*! - \class JsonDbClient - - \brief The JsonDbClient class provides a client interface which connects to the JsonDb server. -*/ - -/*! - \enum JsonDbClient::NotifyType - - This type is used to subscribe to certain notification actions. - - \value NotifyCreate Send notification when an object is created. - \value NotifyUpdate Send notification when an object is updated. - \value NotifyRemove Send notification when an object is removed. - - \sa registerNotification() -*/ - -/*! - \enum JsonDbClient::Status - - This enum describes current database connection status. - - \value Null Not connected. - \value Connecting Connection to the database is being established. - \value Ready Connection established. - \value Error Disconnected due to an error. -*/ - - -/*! \internal - Returns the index of a method, even if method is not normalized. - Returns -1 if there's no such method. - - \a mo must not be 0 - \a method can be 0 -*/ -static int indexOfMethod(const QMetaObject *mo, const char *method) -{ - Q_ASSERT(mo); - if (!method) - return -1; - - int idx = mo->indexOfMethod(method + 1); - if (idx < 0) { - QByteArray norm = QMetaObject::normalizedSignature(method); - idx = mo->indexOfMethod(norm.constData() + 1); - } - - return idx; -} - -/*! - \internal - - Constructs a new client object using a given \a connection and \a parent. -*/ -JsonDbClient::JsonDbClient(JsonDbConnection *connection, QObject *parent) - : QObject(parent), d_ptr(new JsonDbClientPrivate(this)) -{ - Q_D(JsonDbClient); - d->init(connection); -} - -/*! - Constructs a new client object and connects via the local socket with a - given name \a socketName and a given \a parent. -*/ -JsonDbClient::JsonDbClient(const QString &socketName, QObject *parent) - : QObject(parent) -{ - JsonDbConnection *connection = new JsonDbConnection(this); - d_ptr.reset(new JsonDbClientPrivate(this)); - Q_D(JsonDbClient); - d->init(connection); - connection->connectToServer(socketName); -} - -/*! - Constructs a new client object and connects via the default local socket - and a given \a parent. -*/ -JsonDbClient::JsonDbClient(QObject *parent) - : QObject(parent), d_ptr(new JsonDbClientPrivate(this)) -{ - Q_D(JsonDbClient); - JsonDbConnection *connection = JsonDbConnection::instance(); - if (connection->thread() != thread()) - connection = new JsonDbConnection(this); - d->init(connection); - d->connection->connectToServer(); -} - -/*! - Destroys the JsonDbClient object. -*/ -JsonDbClient::~JsonDbClient() -{ -} - -/*! - \internal -*/ -bool JsonDbClient::event(QEvent *event) -{ - if (event->type() == QEvent::ThreadChange) { - Q_D(JsonDbClient); - if (JsonDbConnection::instance() == d->connection) { - d->init(new JsonDbConnection(this)); - d->connection->connectToServer(); - } - } else if (event->type() == QEvent::Timer) { - Q_D(JsonDbClient); - QTimerEvent *te = static_cast<QTimerEvent *>(event); - if (te->timerId() == d->timeoutTimerId) { - killTimer(d->timeoutTimerId); - d->timeoutTimerId = -1; - d->_q_timeout(); - } - } - return QObject::event(event); -} - -/*! - \fn void JsonDbClient::statusChanged() - The signal is emitted when the connection status is changed. - \sa status, connectToServer(), errorString() -*/ -/*! - \property JsonDbClient::status - \brief Returns the current database connection status. - \sa disconnected() -*/ -JsonDbClient::Status JsonDbClient::status() const -{ - return d_func()->status; -} - -void JsonDbClientPrivate::_q_statusChanged() -{ - Q_Q(JsonDbClient); - JsonDbClient::Status newStatus = status; - switch (connection->status()) { - case JsonDbConnection::Disconnected: - if (status != JsonDbClient::Error) { - requestQueue.unite(sentRequestQueue); - sentRequestQueue.clear(); - if (autoReconnect) { - newStatus = JsonDbClient::Connecting; - if (timeoutTimerId == -1) - timeoutTimerId = q->startTimer(5000); - } else { - newStatus = JsonDbClient::Error; - } - } - break; - case JsonDbConnection::Connecting: - case JsonDbConnection::Authenticating: - newStatus = JsonDbClient::Connecting; - break; - case JsonDbConnection::Ready: - newStatus = JsonDbClient::Ready; - _q_processQueue(); - break; - case JsonDbConnection::Error: - newStatus = JsonDbClient::Error; - break; - } - if (status != newStatus) { - status = newStatus; - emit q->statusChanged(); - } -} - -void JsonDbClientPrivate::_q_timeout() -{ - if (status != JsonDbClient::Error) - connection->connectToServer(); -} - -void JsonDbClientPrivate::_q_processQueue() -{ - Q_Q(JsonDbClient); - - if (requestQueue.isEmpty()) - return; - if (connection->status() != JsonDbConnection::Ready) - return; - - QMap<int, QVariantMap>::iterator it = requestQueue.begin(); - int requestId = it.key(); - QVariantMap request = it.value(); - requestQueue.erase(it); - - if (!connection->request(requestId, request)) { - requestQueue.insert(requestId, request); - qWarning("qtjsondb: Cannot send request to the server from processQueue!"); - return; - } else { - sentRequestQueue.insert(requestId, request); - } - - if (!requestQueue.isEmpty()) - QMetaObject::invokeMethod(q, "_q_processQueue", Qt::QueuedConnection); -} - -bool JsonDbClientPrivate::send(int requestId, const QVariantMap &request) -{ - if (requestQueue.isEmpty() && connection->request(requestId, request)) { - sentRequestQueue.insert(requestId, request); - return true; - } - requestQueue.insert(requestId, request); - return false; -} - -/*! - Returns true if the client is connected to the database. - \sa status -*/ -bool JsonDbClient::isConnected() const -{ - Q_D(const JsonDbClient); - return d->status == JsonDbClient::Ready; -} - -void JsonDbClientPrivate::init(JsonDbConnection *c) -{ - Q_Q(JsonDbClient); - - if (connection) { - q->disconnect(q, SLOT(_q_statusChanged())); - q->disconnect(q, SLOT(_q_handleNotified(QString,QVariant,QString))); - q->disconnect(q, SLOT(_q_handleResponse(int,QVariant))); - q->disconnect(q, SLOT(_q_handleError(int,int,QString))); - q->disconnect(q, SIGNAL(disconnected())); - } - connection = c; - - _q_statusChanged(); - - q->connect(connection, SIGNAL(statusChanged()), q, SLOT(_q_statusChanged())); - q->connect(connection, SIGNAL(notified(QString,QVariant,QString)), - SLOT(_q_handleNotified(QString,QVariant,QString))); - q->connect(connection, SIGNAL(response(int,QVariant)), - SLOT(_q_handleResponse(int,QVariant))); - q->connect(connection, SIGNAL(error(int,int,QString)), - SLOT(_q_handleError(int,int,QString))); - q->connect(connection, SIGNAL(disconnected()), SIGNAL(disconnected())); -} - -void JsonDbClientPrivate::_q_handleNotified(const QString ¬ifyUuid, const QVariant &v, const QString &action) -{ - Q_Q(JsonDbClient); - QVariantMap vdata = v.toMap(); - if (notifyCallbacks.contains(notifyUuid)) { - NotifyCallback c = notifyCallbacks.value(notifyUuid); - QList<QByteArray> params = c.method.parameterTypes(); - - JsonDbClient::NotifyType type; - if (action == JsonDbString::kCreateStr) { - type = JsonDbClient::NotifyCreate; - } else if (action == JsonDbString::kUpdateStr) { - type = JsonDbClient::NotifyUpdate; - } else if (action == JsonDbString::kRemoveStr) { - type = JsonDbClient::NotifyRemove; - } else if (action == QLatin1String("stateChange")) { - return; - } else { - Q_ASSERT(false); - return; - } - - quint32 stateNumber = quint32(0); // ### TODO - - JsonDbNotification notification(vdata, type, stateNumber); - if (params.size() == 2 && params.at(1) == QByteArray("QtAddOn::JsonDb::JsonDbNotification")) { - c.method.invoke(c.object.data(), Q_ARG(QString, notifyUuid), Q_ARG(JsonDbNotification, notification)); - } else { - c.method.invoke(c.object.data(), Q_ARG(QString, notifyUuid), Q_ARG(QVariant, vdata), Q_ARG(QString, action)); - } - emit q->notified(notifyUuid, vdata, action); - emit q->notified(notifyUuid, notification); - } -} - -void JsonDbClientPrivate::_q_handleResponse(int id, const QVariant &data) -{ - Q_Q(JsonDbClient); - - sentRequestQueue.remove(id); - QHash<int, NotifyCallback>::iterator it = unprocessedNotifyCallbacks.find(id); - if (it != unprocessedNotifyCallbacks.end()) { - NotifyCallback c = it.value(); - unprocessedNotifyCallbacks.erase(it); - QString notifyUuid = data.toMap().value(JsonDbString::kUuidStr).toString(); - notifyCallbacks.insert(notifyUuid, c); - } - QHash<int, Callback>::iterator idsit = ids.find(id); - if (idsit == ids.end()) - return; - Callback c = idsit.value(); - ids.erase(idsit); - if (QObject *object = c.object.data()) { - const QMetaObject *mo = object->metaObject(); - int idx = indexOfMethod(mo, c.successSlot); - if (idx >= 0) { - QMetaMethod method = mo->method(idx); - QList<QByteArray> params = method.parameterTypes(); - const QVariant vdata = data.toMap(); - method.invoke(object, Q_ARG(int, id), Q_ARG(QVariant, vdata)); - } else { - qWarning() << "JsonDbClient: non existent slot" - << (c.successSlot ? QLatin1String(c.successSlot+1) : QLatin1String("<null>")) - << "on" << object; - } - } - emit q->response(id, data); -} - -void JsonDbClientPrivate::_q_handleError(int id, int code, const QString &message) -{ - Q_Q(JsonDbClient); - - sentRequestQueue.remove(id); - unprocessedNotifyCallbacks.remove(id); - - QHash<int, Callback>::iterator it = ids.find(id); - if (it == ids.end()) - return; - Callback c = it.value(); - ids.erase(it); - if (QObject *object = c.object.data()) { - const QMetaObject *mo = object->metaObject(); - int idx = indexOfMethod(mo, c.errorSlot); - if (idx >= 0) - mo->method(idx).invoke(object, Q_ARG(int, id), Q_ARG(int, code), Q_ARG(QString, message)); - } - emit q->error(id, (JsonDbError::ErrorCode)code, message); -} - -/*! - \deprecated - \obsolete -*/ -int JsonDbClient::find(const QVariant &object, QObject *target, const char *successSlot, const char *errorSlot) -{ - Q_D(JsonDbClient); - Q_ASSERT(d->connection); - int id = d->connection->makeRequestId(); - d->ids.insert(id, JsonDbClientPrivate::Callback(target, successSlot, errorSlot)); - QVariantMap request; - request.insert(JsonDbString::kActionStr, JsonDbString::kFindStr); - request.insert(JsonDbString::kObjectStr, object); - request.insert(JsonDbString::kPartitionStr, QString()); - d->send(id, request); - return id; -} - -/*! - \deprecated - \obsolete - Starts a query \a queryString with \a offset and \a limit in partition \a partitionName. - In case of success \a successSlot is triggered on \a target, \a errorSlot is triggered otherwise. -*/ -int JsonDbClient::query(const QString &queryString, int offset, int limit, - const QString &partitionName, QObject *target, const char *successSlot, const char *errorSlot) -{ - Q_D(JsonDbClient); - Q_ASSERT(d->connection); - int id = d->connection->makeRequestId(); - d->ids.insert(id, JsonDbClientPrivate::Callback(target, successSlot, errorSlot)); - QVariantMap request = JsonDbConnection::makeQueryRequest(queryString, offset, limit, QVariantMap(), partitionName); - d->send(id, request); - return id; -} - -/*! - \fn int JsonDbClient::query(const QString &query, int offset = 0, int limit = -1, - const QVariantMap &bindings = QVariantMap(), - const QString &partitionName = QString(), - QObject *target = 0, const char *successSlot = 0, const char *errorSlot = 0); - - Starts a database \a query in a given \a partitionName. - - This function starts a query, skipping the first matching \a offset items, - and asynchronously returning up to \a limit items. Returns the reference id - of the query. - - \a bindings can be used to pass e.g. user-provided data to query constraints, e.g. - \code - void get(const QString &name) - { - QString queryString = QLatin1String("[?_type=\"Person\"][?name=%name]"); - QVariantMap bindings; - bindings.insert(QLatin1String("name"), name); - client->query(queryString, 0, -1, bindings); - } - \endcode - - If the query fails (e.g. there is a syntax error in the \a query string) \a - errorSlot is called (if given) on \a target in addition to the error() - signal. The \a errorSlot should be a slot with the following format: \c {void - errorSlot(int id, int code, const QString &message)} - - When the query result is ready \a successSlot is called (if given) on \a - target in addition to the response() signal. The \a successSlot should be a - slot with the following format: \c {void successSlot(int id, const QVariant - &object)} - - Note that this function returns the whole response and hence is very - inefficient for large datasets, in general a query() function should be preferred instead. - - A successful response object will include the following properties: - - \list - \li \c data: a list of objects matching the query - \li \c length: the number of returned objects - \li \c offset: the offset of the returned objects in the list of all objects matching the query. - \endlist - - \sa query(), JsonDbQuery, response(), error() -*/ -// \sa query() doesn't generate proper link, but I still mention it so that we -// can change it when qdoc3 is fixed -int JsonDbClient::query(const QString &queryString, int offset, int limit, - const QMap<QString,QVariant> &bindings, - const QString &partitionName, QObject *target, const char *successSlot, const char *errorSlot) -{ - Q_D(JsonDbClient); - Q_ASSERT(d->connection); - int id = d->connection->makeRequestId(); - d->ids.insert(id, JsonDbClientPrivate::Callback(target, successSlot, errorSlot)); - QVariantMap request = JsonDbConnection::makeQueryRequest(queryString, offset, limit, bindings, partitionName); - d->send(id, request); - return id; -} - -/*! - Constructs and returns an object for executing a query. - - \sa JsonDbQuery -*/ -JsonDbQuery *JsonDbClient::query() -{ - return new JsonDbQuery(this, this); -} - -/*! - Sends a request to insert \a object into the database. Returns the reference id of the query. - - Given \a object is created in partition \a partitionName. - - Upon success, invokes \a successSlot of \a target, if provided, else emits \c response(). - On error, invokes \a errorSlot of \a target, if provided, else emits \c error(). - - A successful response will include the following properties: - - \list - \li \c _uuid: the unique id of the created object - \li \c _version: the version of the created object - \endlist - - \sa response() - \sa error() -*/ -int JsonDbClient::create(const QVariant &object, const QString &partitionName, QObject *target, const char *successSlot, const char *errorSlot) -{ - Q_D(JsonDbClient); - Q_ASSERT(d->connection); - - int id = d->connection->makeRequestId(); - - d->ids.insert(id, JsonDbClientPrivate::Callback(target, successSlot, errorSlot)); - if (object.type() == QVariant::Map - && object.toMap().value(JsonDbString::kTypeStr).toString() == JsonDbString::kNotificationTypeStr) - d->unprocessedNotifyCallbacks.insert(id, JsonDbClientPrivate::NotifyCallback()); - - QVariantMap request = JsonDbConnection::makeCreateRequest(object, partitionName); - d->send(id, request); - - return id; -} - -/*! - Sends a request to update \a object in partition \a partitionName. Returns the reference id of the query. - - Upon success, invokes \a successSlot of \a target, if provided, else emits \c response(). - On error, invokes \a errorSlot of \a target, if provided, else emits \c error(). - - A successful response will include the following properties: - - \list - \li \c _uuid: the unique id of the updated object - \li \c _version: the version of the updated object - \endlist - - \sa response() - \sa error() -*/ -int JsonDbClient::update(const QVariant &object, const QString &partitionName, QObject *target, const char *successSlot, const char *errorSlot) -{ - Q_D(JsonDbClient); - Q_ASSERT(d->connection); - - int id = d->connection->makeRequestId(); - - d->ids.insert(id, JsonDbClientPrivate::Callback(target, successSlot, errorSlot)); - - QVariantMap request = JsonDbConnection::makeUpdateRequest(object, partitionName); - d->send(id, request); - - return id; -} - -/*! - Sends a request to remove \a object from partition \a partitionName. Returns the reference id of the query. - - Upon success, invokes \a successSlot of \a target, if provided, else emits \c response(). - On error, invokes \a errorSlot of \a target, if provided, else emits \c error(). - - A successful response will include the following properties: - - \list - \li \c _uuid: the unique id of the removed object - \endlist - - \sa response() - \sa error() -*/ -int JsonDbClient::remove(const QVariant &object, const QString &partitionName, QObject *target, const char *successSlot, const char *errorSlot) -{ - Q_D(JsonDbClient); - Q_ASSERT(d->connection); - - int id = d->connection->makeRequestId(); - - d->ids.insert(id, JsonDbClientPrivate::Callback(target, successSlot, errorSlot)); - if (object.toMap().value(JsonDbString::kTypeStr).toString() == JsonDbString::kNotificationTypeStr) - d->notifyCallbacks.remove(object.toMap().value(JsonDbString::kUuidStr).toString()); - - QVariantMap request; - if (object.type() == QVariant::String) { - QString queryString = object.toString(); - QVariantMap query; - query.insert(JsonDbString::kQueryStr, queryString); - request = JsonDbConnection::makeRemoveRequest(query, partitionName); - } else { - request = JsonDbConnection::makeRemoveRequest(object, partitionName); - } - d->send(id, request); - - return id; -} - -/*! - \deprecated - \obsolete - Creates a notification for a given \a query and notification \a types. - - When an object that is matched a \a query is created/update/removed (depending on the given - \a types), the \a notifySlot will be invoken on \a notifyTarget. - - Upon success, invokes \a responseSuccessSlot of \a responseTarget, if provided, else emits \c response(). - On error, invokes \a responseErrorSlot of \a responseTarget, if provided, else emits \c error(). -*/ -int JsonDbClient::notify(NotifyTypes types, const QString &query, - const QString &partitionName, - QObject *notifyTarget, const char *notifySlot, - QObject *responseTarget, const char *responseSuccessSlot, const char *responseErrorSlot) -{ - Q_D(JsonDbClient); - Q_ASSERT(d->connection); - - QVariantList actions; - if (types & JsonDbClient::NotifyCreate) - actions.append(JsonDbString::kCreateStr); - if (types & JsonDbClient::NotifyRemove) - actions.append(JsonDbString::kRemoveStr); - if (types & JsonDbClient::NotifyUpdate) - actions.append(JsonDbString::kUpdateStr); - - QVariantMap create; - create.insert(JsonDbString::kTypeStr, JsonDbString::kNotificationTypeStr); - create.insert(JsonDbString::kQueryStr, query); - create.insert(JsonDbString::kActionsStr, actions); - create.insert(JsonDbString::kPartitionStr, partitionName); - - int id = d->connection->makeRequestId(); - - d->ids.insert(id, JsonDbClientPrivate::Callback(responseTarget, responseSuccessSlot, responseErrorSlot)); - if (notifyTarget) { - const QMetaObject *mo = notifyTarget->metaObject(); - int idx = indexOfMethod(mo, notifySlot); - if (idx < 0) { - qWarning("JsonDbClient::notify: No such method %s::%s", - mo->className(), notifySlot ? notifySlot + 1 : "<null>"); - } else { - d->unprocessedNotifyCallbacks.insert(id, JsonDbClientPrivate::NotifyCallback(notifyTarget, mo->method(idx))); - } - } else { - d->unprocessedNotifyCallbacks.insert(id, JsonDbClientPrivate::NotifyCallback()); - } - - QVariantMap request = JsonDbConnection::makeCreateRequest(create); - d->send(id, request); - - return id; -} - -/*! - Creates a notification for a given notification \a types and \a query in a \a partition. - - When an object that is matched a \a query is created/update/removed (depending on the given - \a types), the \a notifySlot will be invoken on \a notifyTarget. - - Upon success, invokes \a responseSuccessSlot of \a responseTarget, if provided, else emits \c response(). - On error, invokes \a responseErrorSlot of \a responseTarget, if provided, else emits \c error(). - - \a notifySlot has the following signature notifySlot(const QString ¬ifyUuid, const JsonDbNotification ¬ification) - - Returns a uuid of a notification object that is passed as notifyUuid argument to the \a notifySlot. - - \sa unregisterNotification(), notified(), JsonDbNotification -*/ -QString JsonDbClient::registerNotification(NotifyTypes types, const QString &query, const QString &partition, - QObject *notifyTarget, const char *notifySlot, - QObject *responseTarget, const char *responseSuccessSlot, const char *responseErrorSlot) -{ - Q_D(JsonDbClient); - Q_ASSERT(d->connection); - - QVariantList actions; - if (types & JsonDbClient::NotifyCreate) - actions.append(JsonDbString::kCreateStr); - if (types & JsonDbClient::NotifyRemove) - actions.append(JsonDbString::kRemoveStr); - if (types & JsonDbClient::NotifyUpdate) - actions.append(JsonDbString::kUpdateStr); - - QString uuid = QUuid::createUuid().toString(); - QVariantMap create; - create.insert(JsonDbString::kUuidStr, uuid); - create.insert(JsonDbString::kTypeStr, JsonDbString::kNotificationTypeStr); - create.insert(JsonDbString::kQueryStr, query); - create.insert(JsonDbString::kActionsStr, actions); - create.insert(JsonDbString::kPartitionStr, partition); - - int id = d->connection->makeRequestId(); - - d->ids.insert(id, JsonDbClientPrivate::Callback(responseTarget, responseSuccessSlot, responseErrorSlot)); - if (notifyTarget) { - const QMetaObject *mo = notifyTarget->metaObject(); - int idx = indexOfMethod(mo, notifySlot); - if (idx < 0) { - qWarning("JsonDbClient::notify: No such method %s::%s", - mo->className(), notifySlot ? notifySlot + 1 : "<null>"); - } else { - d->unprocessedNotifyCallbacks.insert(id, JsonDbClientPrivate::NotifyCallback(notifyTarget, mo->method(idx))); - } - } else { - d->unprocessedNotifyCallbacks.insert(id, JsonDbClientPrivate::NotifyCallback()); - } - - QVariantMap request = JsonDbConnection::makeUpdateRequest(create); - d->send(id, request); - - return uuid; -} - -/*! - Deletes a notification for a given \a notifyUuid. - - \sa registerNotification() -*/ -void JsonDbClient::unregisterNotification(const QString ¬ifyUuid) -{ - Q_D(JsonDbClient); - Q_ASSERT(d->connection); - - QVariantMap object; - object.insert(JsonDbString::kUuidStr, notifyUuid); - object.insert(JsonDbString::kTypeStr, JsonDbString::kNotificationTypeStr); - - int id = d->connection->makeRequestId(); - QVariantMap request = JsonDbConnection::makeRemoveRequest(object); - d->send(id, request); -} - -/*! - Sends a request to retrieve a description of changes since - database state \a stateNumber. Limits the change descriptions to - those for the types in \a types, if not empty in a given \a partitionName. - Returns the reference id of the query. - - Upon success, invokes \a successSlot of \a target, if provided, else emits \c response(). - On error, invokes \a errorSlot of \a target, if provided, else emits \c error(). - - \sa response() - \sa error() -*/ -int JsonDbClient::changesSince(int stateNumber, QStringList types, - const QString &partitionName, QObject *target, const char *successSlot, const char *errorSlot) -{ - Q_D(JsonDbClient); - Q_ASSERT(d->connection); - - int id = d->connection->makeRequestId(); - - d->ids.insert(id, JsonDbClientPrivate::Callback(target, successSlot, errorSlot)); - - QVariantMap request = JsonDbConnection::makeChangesSinceRequest(stateNumber, types, partitionName); - d->send(id, request); - - return id; -} - -/*! - Constructs and returns an object for executing a changesSince query. - - \sa JsonDbChangesSince -*/ -JsonDbChangesSince *JsonDbClient::changesSince() -{ - return new JsonDbChangesSince(this, this); -} - -/*! - \property JsonDbClient::autoReconnect - - \brief Specifies whether to reconnect when server connection is lost. -*/ -void JsonDbClient::setAutoReconnect(bool reconnect) -{ - Q_D(JsonDbClient); - d->autoReconnect = reconnect; -} - -bool JsonDbClient::autoReconnect() const -{ - return d_func()->autoReconnect; -} - -/*! - Connects to the server if not connected. - \sa autoReconnect(), disconnectFromServer() -*/ -void JsonDbClient::connectToServer() -{ - Q_D(JsonDbClient); - if (d->status == JsonDbClient::Connecting || d->status == JsonDbClient::Ready) - return; - d->connection->connectToServer(); -} - -/*! - Disconnects to the server if connected. - \sa autoReconnect(), connectToServer(), errorString() -*/ -void JsonDbClient::disconnectFromServer() -{ - Q_D(JsonDbClient); - if (d->status != JsonDbClient::Ready) - return; - d->connection->disconnectFromServer(); -} - -/*! - Returns a human readable description of the last database connection error. -*/ -QString JsonDbClient::errorString() const -{ - return d_func()->connection->errorString(); -} - -/*! - \fn void JsonDbClient::notified(const QString ¬ifyUuid, const JsonDbNotification ¬ification) - - Signal that a notification has been received. The notification object must - have been created previously, usually with the \c registerNotification() - function. The \a notifyUuid field is the uuid of the notification object. - The \a notification object contains information describing the event. - - \sa registerNotification() -*/ - -/*! - \fn void JsonDbClient::notified(const QString ¬ifyUuid, const QVariant &object, const QString &action) - - \deprecated - \obsolete - - Signal that a notification has been received. The notification - object must have been created previously, usually with the - \c create() function (an object with ``_type="notification"``). The - \a notifyUuid field is the uuid of the notification object. The - \a object field is the actual database object and the \a action - field is the action that started the notification (one of - "create", "update", or "remove"). - - \sa notify(), create() -*/ - -/*! - \fn void JsonDbClient::notified(const QString ¬ify_uuid, const QsonObject &object, const QString &action) - - \deprecated - \obsolete - - Signal that a notification has been received. The notification - object must have been created previously, usually with the - \c create() function (an object with ``_type="notification"``). The - \a notify_uuid field is the uuid of the notification object. The - \a object field is the actual database object and the \a action - field is the action that started the notification (one of - "create", "update", or "remove"). - - \sa notify(), create() -*/ - -/*! - \fn void JsonDbClient::response(int id, const QVariant &object) - - Signal that a response to a request has been received from the - database. The \a id parameter will match with the return result - of the request to the database. The \a object parameter depends - on the type of the original request. - - \sa create(), update(), remove() -*/ - -/*! - \fn void JsonDbClient::response(int id, const QsonObject &object) - - \deprecated - \obsolete - - Signal that a response to a request has been received from the - database. The \a id parameter will match with the return result - of the request to the database. The \a object parameter depends - on the type of the original request. - - \sa create(), update(), remove() -*/ - -/*! - \fn void JsonDbClient::error(int id, int code, const QString &message) - - Signals an error in the database request. The \a id parameter - will match the return result of the original request to the - database. The \a code and \a message parameters indicate the error. - - \a code is an error code from JsonDbError::ErrorCode - - \sa create(), update(), remove(), JsonDbError::ErrorCode -*/ - -/*! - \fn void JsonDbClient::disconnected() - - This signal is emitted when the client connection is broken. JsonDbClient - automatically will try to reconnect, so this signal is just a convenience. - - \sa status, errorString(), connectToServer() -*/ - -/*! - \fn int JsonDbClient::changesSince(int stateNumber, QStringList types, QObject *target, const char *successSlot, const char *errorSlot) - \deprecated - \obsolete -*/ -/*! - \fn int JsonDbClient::notify(NotifyTypes types, const QString &query, - QObject *notifyTarget = 0, const char *notifySlot = 0, - QObject *responseTarget = 0, const char *responseSuccessSlot = 0, const char *responseErrorSlot = 0) - \deprecated - \obsolete - Registers notification for a \a query on \a types. - Callback \a notifySlot is triggered on \a notifyTarget. - When notification is created, \a responseSuccessSlot or \a responseErrorSlot is triggered on \a responseTarget. - \sa registerNotification() -*/ -/*! - \fn int JsonDbClient::query(const QString &query, int offset, int limit, QObject *target, const char *successSlot, const char *errorSlot) - \deprecated - \obsolete -*/ -/*! - \fn int JsonDbClient::remove(const QsonObject &object, QObject *target = 0, const char *successSlot = 0, const char *errorSlot = 0) - \deprecated - \obsolete -*/ -/*! - \fn int JsonDbClient::update(const QsonObject &object, QObject *target = 0, const char *successSlot = 0, const char *errorSlot = 0) - \deprecated - \obsolete -*/ - -#include "moc_jsondb-client.cpp" - -QT_END_NAMESPACE_JSONDB diff --git a/src/clientcompat/jsondb-client.h b/src/clientcompat/jsondb-client.h deleted file mode 100644 index 5a7a3e9..0000000 --- a/src/clientcompat/jsondb-client.h +++ /dev/null @@ -1,180 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDB_CLIENT_H -#define JSONDB_CLIENT_H - -#include <QObject> -#include <QVariant> -#include <QList> -#include <QStringList> -#include <QScopedPointer> - -#include "jsondb-global.h" -#include "jsondb-error.h" -#include "jsondb-query.h" - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE_JSONDB - -class QsonObject; - -class JsonDbConnection; -class JsonDbClientPrivate; -class JsonDbNotification; - -class Q_ADDON_JSONDB_EXPORT JsonDbClient : public QObject -{ - Q_OBJECT - Q_PROPERTY(Status status READ status NOTIFY statusChanged) - Q_PROPERTY(bool autoReconnect READ autoReconnect WRITE setAutoReconnect) -public: - JsonDbClient(const QString &socketName, QObject *parent = 0); - JsonDbClient(QObject *parent = 0); - ~JsonDbClient(); - - // this is private api - explicit JsonDbClient(JsonDbConnection *connection, QObject *parent = 0); - - bool isConnected() const; - - enum NotifyType { - NotifyCreate = 0x01, - NotifyUpdate = 0x02, - NotifyRemove = 0x04 - }; - Q_DECLARE_FLAGS(NotifyTypes, NotifyType) - - enum Status { - Null = 0, - Connecting = 1, - Ready = 2, - Error = 3 - }; - Status status() const; - - void setAutoReconnect(bool reconnect); - bool autoReconnect() const; - - void connectToServer(); - void disconnectFromServer(); - - QString errorString() const; - -public slots: - QT_DEPRECATED - int find(const QVariant &query, QObject *target = 0, const char *successSlot = 0, const char *errorSlot = 0); - - int create(const QVariant &object, const QString &partitionName = QString(), - QObject *target = 0, const char *successSlot = 0, const char *errorSlot = 0); - int update(const QVariant &object, const QString &partitionName = QString(), - QObject *target = 0, const char *successSlot = 0, const char *errorSlot = 0); - int remove(const QVariant &object, const QString &partitionName = QString(), - QObject *target = 0, const char *successSlot = 0, const char *errorSlot = 0); - - QT_DEPRECATED - int notify(NotifyTypes types, const QString &query, const QString &partitionName = QString(), - QObject *notifyTarget = 0, const char *notifySlot = 0, - QObject *responseTarget = 0, const char *responseSuccessSlot = 0, const char *responseErrorSlot = 0); - - QString registerNotification(NotifyTypes types, const QString &query, const QString &partitionName = QString(), - QObject *notifyTarget = 0, const char *notifySlot = 0, - QObject *responseTarget = 0, const char *responseSuccessSlot = 0, const char *responseErrorSlot = 0); - void unregisterNotification(const QString ¬ifyUuid); - - int query(const QString &query, int offset, int limit, const QVariantMap &bindings, - const QString &partitionName = QString(), - QObject *target = 0, const char *successSlot = 0, const char *errorSlot = 0); - QT_DEPRECATED - int query(const QString &query, int offset = 0, int limit = -1, - const QString &partitionName = QString(), - QObject *target = 0, const char *successSlot = 0, const char *errorSlot = 0); - int changesSince(int stateNumber, QStringList types = QStringList(), const QString &partitionName = QString(), - QObject *target = 0, const char *successSlot = 0, const char *errorSlot = 0); - - JsonDbQuery *query(); - JsonDbChangesSince *changesSince(); - -Q_SIGNALS: -#ifdef qdoc - void notified(const QString ¬ify_uuid, const JsonDbNotification ¬ification); -#else - void notified(const QString ¬ify_uuid, const QtAddOn::JsonDb::JsonDbNotification ¬ification); -#endif - void response(int id, const QVariant &object); - void error(int id, int code, const QString &message); - - // these three are deprecated and will be removed - void notified(const QString ¬ify_uuid, const QVariant &object, const QString &action); - void notified(const QString ¬ify_uuid, const QsonObject &object, const QString &action); - void readyWrite(); - - void disconnected(); - - // signals for properties - void statusChanged(); - -protected: - bool event(QEvent *); - -private: - Q_DISABLE_COPY(JsonDbClient) - Q_DECLARE_PRIVATE(JsonDbClient) - QScopedPointer<JsonDbClientPrivate> d_ptr; - Q_PRIVATE_SLOT(d_func(), void _q_statusChanged()) - Q_PRIVATE_SLOT(d_func(), void _q_handleResponse(int,QVariant)) - Q_PRIVATE_SLOT(d_func(), void _q_handleError(int,int,QString)) - Q_PRIVATE_SLOT(d_func(), void _q_handleNotified(QString,QVariant,QString)) - Q_PRIVATE_SLOT(d_func(), void _q_timeout()) - Q_PRIVATE_SLOT(d_func(), void _q_processQueue()) -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(JsonDbClient::NotifyTypes) - -QT_END_NAMESPACE_JSONDB - -QT_END_HEADER - -// for compatibility, include struct here that is needed for notifications -#include "jsondb-notification.h" - -#endif // JSONDB_CLIENT_H diff --git a/src/clientcompat/jsondb-client_p.h b/src/clientcompat/jsondb-client_p.h deleted file mode 100644 index 2df217c..0000000 --- a/src/clientcompat/jsondb-client_p.h +++ /dev/null @@ -1,127 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDBCLIENT_P_H -#define JSONDBCLIENT_P_H - -#include "jsondb-global.h" - -#include <QMetaMethod> -#include <QPointer> -#include <QTimer> - -#include "jsondb-client.h" - -QT_BEGIN_NAMESPACE_JSONDB - -/*! - \class JsonDbClientPrivate - \internal -*/ -class JsonDbClientPrivate -{ - Q_DECLARE_PUBLIC(JsonDbClient) -public: - JsonDbClientPrivate(JsonDbClient *q) - : q_ptr(q), connection(0), status(JsonDbClient::Null), autoReconnect(true), - timeoutTimerId(-1) - { } - - ~JsonDbClientPrivate() - { } - - void _q_statusChanged(); - void _q_handleNotified(const QString &, const QVariant &, const QString &); - void _q_handleResponse(int id, const QVariant &data); - void _q_handleError(int id, int code, const QString &message); - void _q_timeout(); - void _q_processQueue(); - - JsonDbClient *q_ptr; - JsonDbConnection *connection; - - JsonDbClient::Status status; - bool autoReconnect; - - QMap<int, QVariantMap> requestQueue; - QMap<int, QVariantMap> sentRequestQueue; - - struct Callback - { - QPointer<QObject> object; - const char *successSlot; - const char *errorSlot; - - inline Callback(QObject *obj, const char *success, const char *error) - : object(obj), successSlot(success), errorSlot(error) - { -#ifdef _DEBUG - if (obj) { - if (successSlot && obj->metaObject()->indexOfMethod(QMetaObject::normalizedSignature(successSlot).constData()+1) < 0) - qWarning() << "JsonDbClient: passing non existent success slot" << QLatin1String(successSlot+1); - if (errorSlot && obj->metaObject()->indexOfMethod(QMetaObject::normalizedSignature(errorSlot).constData()+1) < 0) - qWarning() << "JsonDbClient: passing non existent error slot" << QLatin1String(errorSlot+1); - } -#endif - } - }; - QHash<int, Callback> ids; - - struct NotifyCallback - { - QPointer<QObject> object; - QMetaMethod method; - NotifyCallback(QObject *obj = 0, QMetaMethod m = QMetaMethod()) - : object(obj), method(m) { } - }; - - QHash<int, NotifyCallback> unprocessedNotifyCallbacks; - QHash<QString, NotifyCallback> notifyCallbacks; - - int timeoutTimerId; - - void init(JsonDbConnection *connection); - bool send(int requestId, const QVariantMap &request); -}; - -QT_END_NAMESPACE_JSONDB - -#endif // JSONDBCLIENT_P_H diff --git a/src/clientcompat/jsondb-connection.cpp b/src/clientcompat/jsondb-connection.cpp deleted file mode 100644 index 45b6310..0000000 --- a/src/clientcompat/jsondb-connection.cpp +++ /dev/null @@ -1,555 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "jsondb-strings_p.h" -#include "jsondb-error.h" -#include "jsondb-oneshot_p.h" -#include "jsondb-connection_p.h" -#include "jsondb-connection_p_p.h" -#include "jsondbsocketname_p.h" - -#include "qjsonobject.h" -#include "qjsonarray.h" - -QT_BEGIN_NAMESPACE_JSONDB - -Q_GLOBAL_STATIC(JsonDbConnection, qtjsondbConnection) - -/*! - \internal - \class JsonDbConnection - - \brief The JsonDbConnection class provides a connection to the - database server. Generally used via \c class JsonDbClient. - - \sa JsonDbClient -*/ - -/*! - Returns a singleton instance of \c JsonDbConnection. -*/ -JsonDbConnection *JsonDbConnection::instance() -{ - JsonDbConnection *c = qtjsondbConnection(); - return c; -} - -/*! - Waits up to \a msecs milliseconds for the connection to the database to be completed. - Returns true if connected. -*/ -bool JsonDbConnection::waitForConnected(int msecs) -{ - Q_D(JsonDbConnection); - QIODevice *device = d->mStream.device(); - if (QLocalSocket *socket = qobject_cast<QLocalSocket *>(device)) - return socket->waitForConnected(msecs); - else if (QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(device)) - return socket->waitForConnected(msecs); - return false; -} - -/*! - Waits up to \a msecs milliseconds for the connection to the database to be closed. - Returns true if disconnected. -*/ -bool JsonDbConnection::waitForDisconnected(int msecs) -{ - Q_D(JsonDbConnection); - QIODevice *device = d->mStream.device(); - if (QLocalSocket *socket = qobject_cast<QLocalSocket *>(device)) - return socket->waitForDisconnected(msecs); - else if (QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(device)) - return socket->waitForDisconnected(msecs); - return false; -} - -bool JsonDbConnection::waitForBytesWritten(int msecs) -{ - Q_D(JsonDbConnection); - QIODevice *device = d->mStream.device(); - if (QLocalSocket *socket = qobject_cast<QLocalSocket *>(device)) - return socket->waitForBytesWritten(msecs); - else if (QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(device)) - return socket->waitForBytesWritten(msecs); - return false; -} - -QVariantMap JsonDbConnection::makeQueryRequest(const QString &queryString, int offset, int limit, const QString &partitionName) -{ - return makeQueryRequest(queryString, offset, limit, QVariantMap(), partitionName); -} - -QVariantMap JsonDbConnection::makeQueryRequest(const QString &queryString, int offset, int limit, - const QVariantMap &bindings, - const QString &partitionName) -{ - QVariantMap request; - request.insert(JsonDbString::kActionStr, JsonDbString::kFindStr); - QVariantMap object; - object.insert(JsonDbString::kQueryStr, queryString); - if (offset != 0) - object.insert(JsonDbString::kOffsetStr, offset); - if (limit != -1) - object.insert(JsonDbString::kLimitStr, limit); - if (!bindings.isEmpty()) - object.insert(QLatin1String("bindings"), bindings); - request.insert(JsonDbString::kObjectStr, object); - request.insert(JsonDbString::kPartitionStr, partitionName); - return request; -} - -QVariantMap JsonDbConnection::makeCreateRequest(const QVariant &object, const QString &partitionName) -{ - QVariantMap request; - request.insert(JsonDbString::kActionStr, JsonDbString::kCreateStr); - request.insert(JsonDbString::kObjectStr, object); - request.insert(JsonDbString::kPartitionStr, partitionName); - return request; -} - -QVariantMap JsonDbConnection::makeUpdateRequest(const QVariant &object, const QString &partitionName) -{ - QVariantMap request; - request.insert(JsonDbString::kActionStr, JsonDbString::kUpdateStr); - request.insert(JsonDbString::kObjectStr, object); - request.insert(JsonDbString::kPartitionStr, partitionName); - return request; -} - -QVariantMap JsonDbConnection::makeRemoveRequest(const QVariant &object, const QString &partitionName) -{ - QVariantMap request; - request.insert(JsonDbString::kActionStr, JsonDbString::kRemoveStr); - request.insert(JsonDbString::kObjectStr, object); - request.insert(JsonDbString::kPartitionStr, partitionName); - return request; -} - -QVariantMap JsonDbConnection::makeNotification(const QString &query, const QVariantList &actions, - const QString &partitionName) -{ - QVariantMap notification; - notification.insert(JsonDbString::kTypeStr, - JsonDbString::kNotificationTypeStr); - notification.insert(JsonDbString::kQueryStr, query); - notification.insert(JsonDbString::kActionsStr, actions); - notification.insert(JsonDbString::kPartitionStr, partitionName); - return notification; -} - -QVariantMap JsonDbConnection::makeChangesSinceRequest(int stateNumber, const QStringList &types, - const QString &partitionName) -{ - QVariantMap request; - request.insert(JsonDbString::kActionStr, JsonDbString::kChangesSinceStr); - QVariantMap object; - object.insert(JsonDbString::kStateNumberStr, stateNumber); - if (!types.isEmpty()) - object.insert(JsonDbString::kTypesStr, types); - request.insert(JsonDbString::kObjectStr, object); - request.insert(JsonDbString::kPartitionStr, partitionName); - return request; -} - -/***************************************************************************/ - -/*! - Constructs a \c JsonDbConnection. -*/ -JsonDbConnection::JsonDbConnection(QObject *parent) - : QObject(parent), d_ptr(new JsonDbConnectionPrivate(this)) -{ -} - -JsonDbConnection::~JsonDbConnection() -{ - Q_D(JsonDbConnection); - // JsonStreams don't own the socket - d->mStream.setDevice(0); -} - -JsonDbConnection::Status JsonDbConnection::status() const -{ - return d_func()->status; -} - -QString JsonDbConnection::errorString() const -{ - return d_func()->errorString; -} - -/*! - Connects to the named local socket \a socketName. -*/ -void JsonDbConnection::connectToServer(const QString &socketName) -{ - Q_D(JsonDbConnection); - - if (d->status != JsonDbConnection::Disconnected) - return; - - QString name = socketName; - if (name.isEmpty()) - name = QLatin1String(::getenv("JSONDB_SOCKET")); - if (name.isEmpty()) - name = QStringLiteral(JSONDB_SOCKET_NAME_STRING); - - d->socket = new QLocalSocket(this); - connect(d->socket, SIGNAL(disconnected()), this, SLOT(_q_onDisconnected())); - connect(d->socket, SIGNAL(connected()), this, SLOT(_q_onConnected())); - connect(d->socket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(_q_onError(QLocalSocket::LocalSocketError))); - - d->status = JsonDbConnection::Connecting; - emit statusChanged(); - - d->socket->connectToServer(name); - - // local socket already emitted connected() signal - if (d->status != JsonDbConnection::Ready && d->status != JsonDbConnection::Disconnected) { - d->status = JsonDbConnection::Connecting; - emit statusChanged(); - } -} - -/*! - Connects to the databsae via a TCP connection to \a hostname and \a port. -*/ -void JsonDbConnection::connectToHost(const QString &hostname, quint16 port) -{ - Q_D(JsonDbConnection); - if (d->status == JsonDbConnection::Ready) - return; - - d->tcpSocket = new QTcpSocket(this); - connect(d->tcpSocket, SIGNAL(disconnected()), this, SLOT(_q_onDisconnected())); - connect(d->tcpSocket, SIGNAL(connected()), this, SLOT(_q_onConnected())); - d->tcpSocket->connectToHost(hostname, port); - d->status = JsonDbConnection::Connecting; - emit statusChanged(); -} - -/*! - Disconnect from the server. -*/ -void JsonDbConnection::disconnectFromServer() -{ - Q_D(JsonDbConnection); - if (d->status == JsonDbConnection::Disconnected) - return; - - if (d->socket) - d->socket->disconnectFromServer(); - - d->status = JsonDbConnection::Disconnected; -} - - -void JsonDbConnectionPrivate::_q_onConnected() -{ - Q_Q(JsonDbConnection); - Q_ASSERT(socket || tcpSocket); - - if (socket) - mStream.setDevice(socket); - else - mStream.setDevice(tcpSocket); - QObject::disconnect(&mStream, SIGNAL(receive(QJsonObject)), q, SLOT(_q_onReceiveMessage(QJsonObject))); - QObject::connect(&mStream, SIGNAL(receive(QJsonObject)), q, SLOT(_q_onReceiveMessage(QJsonObject))); - - status = JsonDbConnection::Ready; - emit q->statusChanged(); - emit q->connected(); -} - -void JsonDbConnectionPrivate::_q_onDisconnected() -{ - Q_Q(JsonDbConnection); - mStream.setDevice(0); - - errorString = socket ? socket->errorString() : tcpSocket->errorString(); - status = JsonDbConnection::Disconnected; - emit q->statusChanged(); - emit q->disconnected(); -} - -void JsonDbConnectionPrivate::_q_onError(QLocalSocket::LocalSocketError error) -{ - Q_Q(JsonDbConnection); - errorString = socket ? socket->errorString() : tcpSocket->errorString(); - switch (error) { - case QLocalSocket::ConnectionRefusedError: - case QLocalSocket::ServerNotFoundError: - case QLocalSocket::SocketAccessError: - case QLocalSocket::ConnectionError: - case QLocalSocket::UnknownSocketError: { - if (status != JsonDbConnection::Disconnected) { - status = JsonDbConnection::Disconnected; - emit q->statusChanged(); - } - break; - } - case QLocalSocket::DatagramTooLargeError: - // I think this should never happen. - qWarning("qtjsondb: QLocalSocket::DatagramTooLargeError"); - if (status != JsonDbConnection::Disconnected) { - status = JsonDbConnection::Disconnected; - emit q->statusChanged(); - } - break; - default: - break; - } -} - -/*! - \deprecated - - Sends request \a dbrequest to the database and returns the request identification number. -*/ -int JsonDbConnection::request(const QVariantMap &dbrequest) -{ - if(!isConnected()) - return -1; - Q_D(JsonDbConnection); - QVariantMap r = dbrequest; - int newid = makeRequestId(); - r.insert(JsonDbString::kIdStr, newid); - if (!d->mStream.send(QJsonObject::fromVariantMap(r))) - return -1; - d->mId = newid; - return newid; -} - -/*! - Sends \a request with a given \a requestId to the database. - - Returns true if the request was successfully sent. -*/ -bool JsonDbConnection::request(int requestId, const QVariantMap &request) -{ - Q_D(JsonDbConnection); - if (status() != JsonDbConnection::Ready) { - return false; - } - - QVariantMap r = request; - r.insert(JsonDbString::kIdStr, requestId); - - if (r.value(JsonDbString::kActionStr).toString() == JsonDbString::kCreateStr || - r.value(JsonDbString::kActionStr).toString() == JsonDbString::kUpdateStr) - d->protocolAdaptionRequests.append(requestId); - - if (!d->mStream.send(QJsonObject::fromVariantMap(r))) - return false; - return true; -} - -/*! - Returns a new request id. -*/ -int JsonDbConnection::makeRequestId() -{ - return ++d_func()->mId; -} - - -void JsonDbConnectionPrivate::_q_onReceiveMessage(const QJsonObject &qjsonMsg) -{ - Q_Q(JsonDbConnection); - int id = qjsonMsg.value(JsonDbString::kIdStr).toDouble(); - - if (qjsonMsg.contains(JsonDbString::kNotifyStr)) { - QJsonObject nmap = qjsonMsg.value(JsonDbString::kNotifyStr).toObject(); - emit q->notified(qjsonMsg.value(JsonDbString::kUuidStr).toString(), - nmap.value(JsonDbString::kObjectStr).toVariant(), - nmap.value(JsonDbString::kActionStr).toString()); - } else { - QJsonValue qjsonResult = qjsonMsg.value(JsonDbString::kResultStr); - if (qjsonResult.type() == QJsonValue::Object) { - QJsonObject result = qjsonResult.toObject(); - if (protocolAdaptionRequests.contains(id)) { - QJsonObject newResult; - if (static_cast<int>(result.value(JsonDbString::kCountStr).toDouble()) == 1) { - newResult = result.value(JsonDbString::kDataStr).toArray().at(0).toObject(); - newResult.insert(JsonDbString::kCountStr, result.value(JsonDbString::kCountStr)); - newResult.insert(JsonDbString::kStateNumberStr, result.value(JsonDbString::kStateNumberStr)); - } else { - QJsonArray newData; - QJsonArray oldData = result.value(JsonDbString::kDataStr).toArray(); - for (int i = 0; i < oldData.count(); i++) { - QJsonObject d = oldData.at(i).toObject(); - d.insert(JsonDbString::kCountStr, 1); - d.insert(JsonDbString::kStateNumberStr, result.value(JsonDbString::kStateNumberStr)); - newData.append(d); - } - - newResult.insert(JsonDbString::kCountStr, result.value(JsonDbString::kCountStr)); - newResult.insert(JsonDbString::kStateNumberStr, result.value(JsonDbString::kStateNumberStr)); - newResult.insert(JsonDbString::kDataStr, newData); - } - protocolAdaptionRequests.removeOne(id); - result = newResult; - } - - emit q->response(id, result.toVariantMap()); - } else { - QVariantMap emap = qjsonMsg.value(JsonDbString::kErrorStr).toObject().toVariantMap(); - emit q->error(id, - emap.value(JsonDbString::kCodeStr).toInt(), - emap.value(JsonDbString::kMessageStr).toString()); - } - } -} - - -/*! - \deprecated - - \sa JsonDbClient -*/ -void JsonDbConnection::oneShot(const QVariantMap &dbrequest, QObject *receiver, - const char *responseSlot, const char *errorSlot) -{ - JsonDbOneShot *oneShot = new JsonDbOneShot; - oneShot->setParent(this); - - connect(this, SIGNAL(response(int,QVariant)), - oneShot, SLOT(handleResponse(int,QVariant))); - connect(this, SIGNAL(error(int,int,QString)), - oneShot, SLOT(handleError(int,int,QString))); - - if (responseSlot && !connect(oneShot, SIGNAL(response(QVariant)), receiver, responseSlot)) - qCritical() << Q_FUNC_INFO << "failed to connect to slot" << responseSlot; - if (errorSlot && !connect(oneShot, SIGNAL(error(int,QString)), receiver, errorSlot)) - qCritical() << Q_FUNC_INFO << "failed to connect to slot" << errorSlot; - - oneShot->mId = request(dbrequest); - if (!responseSlot && !errorSlot) - oneShot->deleteLater(); -} - -QVariant JsonDbConnection::sync(const QVariantMap &dbrequest) -{ - QVariant result; - QThread syncThread; - JsonDbSyncCall *call = new JsonDbSyncCall(&dbrequest, &result); - - connect(&syncThread, SIGNAL(started()), - call, SLOT(createSyncRequest())); - connect(&syncThread, SIGNAL(finished()), - call, SLOT(deleteLater())); - call->moveToThread(&syncThread); - syncThread.start(); - syncThread.wait(); - return result; -} - -/*! - Returns true if connected to the database. -*/ -bool JsonDbConnection::isConnected() const -{ - Q_D(const JsonDbConnection); - QIODevice *device = d->mStream.device(); - if (!device) - return false; - if (QLocalSocket *socket = qobject_cast<QLocalSocket *>(device)) - return socket->state() == QLocalSocket::ConnectedState; - else if (QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(device)) - return socket->state() == QAbstractSocket::ConnectedState; - - return false; -} - -/*! - \fn void JsonDbConnection::disconnected() - This signal is emitted when the connection to the database is lost. -*/ - -JsonDbSyncCall::JsonDbSyncCall(const QVariantMap &dbrequest, QVariant &result) - : mDbRequest(&dbrequest), mResult(&result), mSyncJsonDbConnection(0) -{ -} - -JsonDbSyncCall::JsonDbSyncCall(const QVariantMap *dbrequest, QVariant *result) - : mDbRequest(dbrequest), mResult(result), mSyncJsonDbConnection(0) -{ -} - -JsonDbSyncCall::~JsonDbSyncCall() -{ - if (mSyncJsonDbConnection) - delete mSyncJsonDbConnection; -} - -void JsonDbSyncCall::createSyncRequest() -{ - mSyncJsonDbConnection = new JsonDbConnection; - mSyncJsonDbConnection->connectToServer(); - - connect(mSyncJsonDbConnection, SIGNAL(response(int,QVariant)), - this, SLOT(handleResponse(int,QVariant))); - connect(mSyncJsonDbConnection, SIGNAL(error(int,int,QString)), - this, SLOT(handleError(int,int,QString))); - mId = mSyncJsonDbConnection->request(*mDbRequest); -} - -void JsonDbSyncCall::handleResponse(int id, const QVariant& data) -{ - if (id == mId) { - *mResult = data; - QThread::currentThread()->quit(); - } -} - -void JsonDbSyncCall::handleError(int id, int code, const QString& message) -{ - if (id == mId) { - qCritical() << "Illegal result" << code << message; - QThread::currentThread()->quit(); - } -} - -#include "moc_jsondb-connection_p.cpp" -#include "moc_jsondb-connection_p_p.cpp" - -QT_END_NAMESPACE_JSONDB diff --git a/src/clientcompat/jsondb-connection_p.h b/src/clientcompat/jsondb-connection_p.h deleted file mode 100644 index 8548552..0000000 --- a/src/clientcompat/jsondb-connection_p.h +++ /dev/null @@ -1,141 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDB_CONNECTION_P_H -#define JSONDB_CONNECTION_P_H - -#include <QObject> -#include <QVariantMap> -#include <QSet> -#include <QStringList> -#include <QLocalSocket> -#include <QTcpSocket> -#include <QScopedPointer> - -#include "jsondb-global.h" - -QT_BEGIN_NAMESPACE_JSONDB - -class JsonDbConnectionPrivate; -class Q_ADDON_JSONDB_EXPORT JsonDbConnection : public QObject -{ - Q_OBJECT - Q_PROPERTY(Status status READ status NOTIFY statusChanged) - -public: - enum Status { - // maintain the order to match QML Component enum values (just in case) - Disconnected = 0, - Null = Disconnected, - Ready = 1, - Connecting = 2, - Error = 3, - - Authenticating = 4 - }; - - static JsonDbConnection *instance(); - - static QVariantMap makeCreateRequest(const QVariant &, const QString &partitionName = QString()); - static QVariantMap makeUpdateRequest(const QVariant &, const QString &partitionName = QString()); - static QVariantMap makeRemoveRequest(const QVariant &, const QString &partitionName = QString()); - static QVariantMap makeQueryRequest(const QString &, int offset = 0, int limit = -1, const QString &partitionName = QString()); - static QVariantMap makeQueryRequest(const QString &, int offset, int limit, - const QVariantMap &bindings, - const QString &partitionName = QString()); - static QVariantMap makeNotification(const QString &, const QVariantList &, const QString &partitionName = QString()); - static QVariantMap makeChangesSinceRequest(int stateNumber, const QStringList &types = QStringList(), const QString &partitionName = QString()); - - JsonDbConnection(QObject *parent = 0); - ~JsonDbConnection(); - - Status status() const; - QString errorString() const; - - // One-shot functions allow you to avoid constructing a JsonDbClient - QT_DEPRECATED - void oneShot( const QVariantMap& dbrequest, QObject *receiver=0, - const char *responseSlot=0, const char *errorSlot=0); - // Synchronized calls pause execution until successful - QVariant sync(const QVariantMap &dbrequest); - - void connectToServer(const QString &socketName = QString()); - void connectToHost(const QString &hostname, quint16 port); - void disconnectFromServer(); - - // General purpose request - int request(const QVariantMap &request); - bool request(int requestId, const QVariantMap &request); - - bool isConnected() const; - Q_DECL_DEPRECATED inline bool connected() const - { return isConnected(); } - - int makeRequestId(); - - bool waitForConnected(int msecs = 30000); - bool waitForDisconnected(int msecs = 30000); - bool waitForBytesWritten(int msecs = 30000); - -signals: - void notified(const QString ¬ify_uuid, const QVariant &object, const QString &action); - void response(int id, const QVariant &data); - void error(int id, int code, const QString &message); - - void connected(); - void disconnected(); - - // signals for properties - void statusChanged(); - -private: - Q_DISABLE_COPY(JsonDbConnection) - Q_DECLARE_PRIVATE(JsonDbConnection) - QScopedPointer<JsonDbConnectionPrivate> d_ptr; - Q_PRIVATE_SLOT(d_func(), void _q_onConnected()) - Q_PRIVATE_SLOT(d_func(), void _q_onDisconnected()) - Q_PRIVATE_SLOT(d_func(), void _q_onError(QLocalSocket::LocalSocketError)) - Q_PRIVATE_SLOT(d_func(), void _q_onReceiveMessage(QJsonObject)) -}; - -QT_END_NAMESPACE_JSONDB - -#endif /* JSONDB_CONNECTION_P_H */ diff --git a/src/clientcompat/jsondb-connection_p_p.h b/src/clientcompat/jsondb-connection_p_p.h deleted file mode 100644 index 888a65f..0000000 --- a/src/clientcompat/jsondb-connection_p_p.h +++ /dev/null @@ -1,113 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDB_CONNECTION_P_P_H -#define JSONDB_CONNECTION_P_P_H - -#include <QObject> -#include <QVariant> -#include <QSet> -#include <QStringList> -#include <QLocalSocket> -#include <QTcpSocket> -#include <QScopedPointer> - -#include <qjsonobject.h> - -#include "jsondb-global.h" -#include "jsondb-connection_p.h" - -#include "jsonstream.h" - -QT_BEGIN_NAMESPACE_JSONDB - -class JsonDbConnectionPrivate -{ - Q_DECLARE_PUBLIC(JsonDbConnection) -public: - JsonDbConnectionPrivate(JsonDbConnection *q) - : q_ptr(q), socket(0), tcpSocket(0), mStream(q), mId(1), status(JsonDbConnection::Null) - { } - ~JsonDbConnectionPrivate() - { } - - void _q_onConnected(); - void _q_onDisconnected(); - void _q_onReceiveMessage(const QJsonObject &); - void _q_onError(QLocalSocket::LocalSocketError error); - - JsonDbConnection *q_ptr; - QLocalSocket *socket; - QTcpSocket *tcpSocket; - QtJsonDbJsonStream::JsonStream mStream; - int mId; - JsonDbConnection::Status status; - QString errorString; - QList<int> protocolAdaptionRequests; -}; - -/*! - * \internal - * The sync class forces a response before the program will continue - */ -class JsonDbSyncCall : public QObject -{ - Q_OBJECT - friend class JsonDbConnection; -public: - QT_DEPRECATED - JsonDbSyncCall(const QVariantMap &dbrequest, QVariant &result); - JsonDbSyncCall(const QVariantMap *dbrequest, QVariant *result); - ~JsonDbSyncCall(); -public slots: - void createSyncRequest(); - void handleResponse( int id, const QVariant& data ); - void handleError( int id, int code, const QString& message ); -private: - int mId; - const QVariantMap *mDbRequest; - QVariant *mResult; - JsonDbConnection *mSyncJsonDbConnection; -}; - -QT_END_NAMESPACE_JSONDB - -#endif /* JSONDB_CONNECTION_P_P_H */ diff --git a/src/clientcompat/jsondb-error.cpp b/src/clientcompat/jsondb-error.cpp deleted file mode 100644 index 0ff6822..0000000 --- a/src/clientcompat/jsondb-error.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "jsondb-global.h" -#include "jsondb-error.h" - -QT_BEGIN_NAMESPACE_JSONDB - -/*! - \class JsonDbError - \brief The JsonDbError class lists possible error codes. - \sa JsonDbError::ErrorCode - */ - -/*! - \enum JsonDbError::ErrorCode - \omitvalue NoError - \value InvalidMessage - Unable to parse the query message. - \value InvalidRequest - Request object doesn't contain correct elements. - \value MissingObject - Invalid or missing "object" field. - \value DatabaseError - Error directly from the database. - \value MissingUUID - Missing id field. - \value MissingType - Missing _type field. - \value MissingQuery - Missing query field. - \value InvalidLimit - Invalid limit field. - \value InvalidOffset - Invalid offset field. - \value MismatchedNotifyId - Request to delete notify doesn't match existing notification. - \value InvalidActions - List of actions supplied to setNotification is invalid. - \value UpdatingStaleVersion - Updating stale version of object. - \value OperationNotPermitted - Operation prohibited by access control policy. - \value FailedSchemaValidation - Object to be created/updated was invalid according to the schema. - \value InvalidMap - The Map definition is invalid. - \value InvalidReduce - The Reduce definition is invalid. - \value InvalidSchemaOperation - Attempted to create a schema that already exists or to remove a schema when there are still objects belonging to the schema's type. - \value InvalidPartition - Invalid partition. - \value InvalidIndexOperation - An error when creating an index object - */ - -QT_END_NAMESPACE_JSONDB diff --git a/src/clientcompat/jsondb-error.h b/src/clientcompat/jsondb-error.h deleted file mode 100644 index f16dc6c..0000000 --- a/src/clientcompat/jsondb-error.h +++ /dev/null @@ -1,88 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDB_ERRORS_H -#define JSONDB_ERRORS_H - -#include "jsondb-global.h" - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE_JSONDB - -class JsonDbError { -public: - enum ErrorCode { - // common errors - NoError = 0, - InvalidRequest = 1, - OperationNotPermitted = 2, - InvalidPartition = 3, - DatabaseConnectionError = 4, - PartitionUnavailable = 5, - - // read / notify errors - MissingQuery = 6, - InvalidMessage= 7, - InvalidLimit = 8, - InvalidOffset = 9, - InvalidStateNumber = 10, - - // write errors - MissingObject = 11, - DatabaseError = 12, - MissingUUID = 13, - MissingType = 14, - UpdatingStaleVersion = 15, - FailedSchemaValidation = 16, - InvalidMap = 17, - InvalidReduce = 18, - InvalidSchemaOperation = 19, - InvalidIndexOperation = 20, - InvalidType = 21 - }; -}; - -QT_END_NAMESPACE_JSONDB - -QT_END_HEADER - -#endif // JSONDB_ERRORS_H diff --git a/src/clientcompat/jsondb-global.h b/src/clientcompat/jsondb-global.h deleted file mode 100644 index 8ba9793..0000000 --- a/src/clientcompat/jsondb-global.h +++ /dev/null @@ -1,93 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#ifndef JSONDB_GLOBAL_H -#define JSONDB_GLOBAL_H - -#include "qglobal.h" - -#ifndef QT_STATIC -# if defined(QT_BUILD_JSONDBCOMPAT_LIB) -# define Q_ADDON_JSONDB_EXPORT Q_DECL_EXPORT -# else -# define Q_ADDON_JSONDB_EXPORT Q_DECL_IMPORT -# endif -#else -# define Q_ADDON_JSONDB_EXPORT -#endif - -#if defined(QT_NAMESPACE) -# define QT_BEGIN_NAMESPACE_JSONDB namespace QT_NAMESPACE { namespace QtAddOn { namespace JsonDb { -# define QT_END_NAMESPACE_JSONDB } } } -# define QT_USE_NAMESPACE_JSONDB using namespace QT_NAMESPACE::QtAddOn::JsonDb; -# define QT_PREPEND_NAMESPACE_JSONDB(name) ::QT_NAMESPACE::QtAddOn::JsonDb::name -#else -# define QT_BEGIN_NAMESPACE_JSONDB namespace QtAddOn { namespace JsonDb { -# define QT_END_NAMESPACE_JSONDB } } -# define QT_USE_NAMESPACE_JSONDB using namespace QtAddOn::JsonDb; -# define QT_PREPEND_NAMESPACE_JSONDB(name) ::QtAddOn::JsonDb::name -#endif - -// a workaround for moc - if there is a header file that doesn't use jsondb -// namespace, we still force moc to do "using namespace" but the namespace have to -// be defined, so let's define an empty namespace here -QT_BEGIN_NAMESPACE_JSONDB -QT_END_NAMESPACE_JSONDB - -// WARNING! All the following macros will be deprecated in a future version of this file. -#define Q_ADDON_JSONDB_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE_JSONDB -#define Q_ADDON_JSONDB_END_NAMESPACE QT_END_NAMESPACE_JSONDB -#define Q_USE_JSONDB_NAMESPACE QT_USE_NAMESPACE_JSONDB -#define Q_ADDON_JSONDB_PREPEND_NAMESPACE(name) QT_PREPEND_NAMESPACE_JSONDB(name) - -# define Q_ADDON_JSONDB_FORWARD_DECLARE_CLASS(name) \ - Q_BEGIN_NAMESPACE_JSONDB class name; Q_END_NAMESPACE_JSONDB \ - using Q_PREPEND_NAMESPACE_JSONDB(name); - -# define Q_FORWARD_DECLARE_STRUCT_JSONDB(name) \ - Q_BEGIN_NAMESPACE_JSONDB struct name; Q_END_NAMESPACE_JSONDB \ - using Q_PREPEND_NAMESPACE_JSONDB(name); - -#define QT_ADDON_JSONDB_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE_JSONDB -#define QT_ADDON_JSONDB_END_NAMESPACE QT_END_NAMESPACE_JSONDB -#define QT_ADDON_JSONDB_USE_NAMESPACE QT_USE_NAMESPACE_JSONDB -#define QT_ADDON_JSONDB_PREPEND_NAMESPACE QT_PREPEND_NAMESPACE_JSONDB - -#endif // JSONDB_GLOBAL_H diff --git a/src/clientcompat/jsondb-notification.cpp b/src/clientcompat/jsondb-notification.cpp deleted file mode 100644 index 045aa6c..0000000 --- a/src/clientcompat/jsondb-notification.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "jsondb-notification.h" -#include "jsondb-client.h" - -QT_BEGIN_NAMESPACE_JSONDB - -/*! - \class JsonDbNotification - - \brief The JsonDbNotification class describes the database notification. - - \sa JsonDbClient::registerNotification() -*/ - -/*! - \internal -*/ -JsonDbNotification::JsonDbNotification(const QVariantMap &object, JsonDbClient::NotifyType action, quint32 stateNumber) - : mObject(object), mAction(action), mStateNumber(stateNumber) -{ -} - -/*! - Returns the object that matched notification. - - If the action() is JsonDbClient::NotifyCreate, the object contains the - full object that was created. - - If the action() is JsonDbClient::NotifyUpdate, the object contains the - latest version of the object. - - If the action() is JsonDbClient::NotifyRemove, the object contains the - _uuid and _version of the object that was removed. -*/ -QVariantMap JsonDbNotification::object() const -{ - return mObject; -} - -/*! - Returns the notification action. -*/ -JsonDbClient::NotifyType JsonDbNotification::action() const -{ - return mAction; -} - -/*! - Returns the state number that corresponds to the object in notification. -*/ -quint32 JsonDbNotification::stateNumber() const -{ - return mStateNumber; -} - -QT_END_NAMESPACE_JSONDB diff --git a/src/clientcompat/jsondb-notification.h b/src/clientcompat/jsondb-notification.h deleted file mode 100644 index 140e9ea..0000000 --- a/src/clientcompat/jsondb-notification.h +++ /dev/null @@ -1,75 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDB_NOTIFICATION_H -#define JSONDB_NOTIFICATION_H - -#include <QVariantMap> - -#include "jsondb-global.h" -#include "jsondb-client.h" - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE_JSONDB - -class Q_ADDON_JSONDB_EXPORT JsonDbNotification -{ -public: - QVariantMap object() const; - JsonDbClient::NotifyType action() const; - quint32 stateNumber() const; - - JsonDbNotification(const QVariantMap &object, JsonDbClient::NotifyType action, quint32 stateNumber); - -protected: - QVariantMap mObject; - JsonDbClient::NotifyType mAction; - quint32 mStateNumber; - - void *reserved; -}; - -QT_END_NAMESPACE_JSONDB - -QT_END_HEADER - -#endif // JSONDB_NOTIFICATION_H diff --git a/src/clientcompat/jsondb-object.cpp b/src/clientcompat/jsondb-object.cpp deleted file mode 100644 index 49384ba..0000000 --- a/src/clientcompat/jsondb-object.cpp +++ /dev/null @@ -1,178 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "jsondb-object.h" - -#include <QCryptographicHash> - -Q_DECLARE_METATYPE(QUuid) - -QT_BEGIN_NAMESPACE_JSONDB - -static QUuid generateUUIDv3(const QString &uri) -{ - QCryptographicHash hash(QCryptographicHash::Md5); - hash.addData(QUuid(0x6ba7b810, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8).toRfc4122()); - hash.addData(uri.toUtf8()); - QByteArray hashResult = hash.result(); - - QUuid result = QUuid::fromRfc4122(hashResult); - - result.data3 &= 0x0FFF; - result.data3 |= (3 << 12); - result.data4[0] &= 0x3F; - result.data4[0] |= 0x80; - - return result; -} - -/*! - \class JsonDbObject - - \brief The JsonDbObject class provides convenience api for constructing - object that should be persisted to QtJsonDb. - - Objects that are persisted to Qt JsonDb are uniquely identified by - \l{http://en.wikipedia.org/wiki/Universally_unique_identifier}{UUID} which - value is stored inside an object in a special property \c{_uuid}. JsonDbObject - provides convenience api for generating uuid for a given object. - - There are several "versions" (variations) of UUID described in the - specification, and for Qt JsonDb the two important ones are the following: - - \list - \li version 3 constructs uuid from a given string (usually, uri) - \li version 4 generates a random uuid - \endlist - - Uuid version 3 makes a deterministic uuid from a given string, that can be - reproduce later on, which is a very useful feature allowing to make a - unique object identifier from a user-given string. For example if one saves - file meta-data into Qt JsonDb, it might be convienient to deterministically - generate uuid from a given file path. In Qt JsonDb this is achieved by - putting the raw string data into a special \c{_id} property and constructing - uuid from the object using JsonDbObject::uuidFromObject() call. - - \code - #include <jsondb-object.h> - - QVariantMap object; - object.insert(QLatin1String("name"), QLatin1String("Tor")); - object.insert(QLatin1String("foo"), 42); - object.insert(QLatin1String("_uuid"), JsonDbObject::uuidFromObject(object)); - - JsonDbClient client; - client.create(object); - \endcode - - \code - #include <jsondb-object.h> - - QMap<QUuid, JsonDbObject> objectsMap; - for (int i = 0; i < 10; ++i) { - JsonDbObject object; - object.insert(QLatin1String("name"), QLatin1String("Tor")); - object.insert(QLatin1String("foo"), 42); - QUuid objectid = JsonDbObject::uuidFromObject(object); - object.setUuid(objectid); - objectsMap.insert(objectid, object); - } - JsonDbClient client; - client.create(objectsMap.values()); - \endcode -*/ - -/*! - Constructs an empty object. -*/ -JsonDbObject::JsonDbObject() -{ } - -/*! - Constructs object from the given \a other QVariantMap. -*/ -JsonDbObject::JsonDbObject(const QVariantMap &other) - : QVariantMap(other) -{ } - -/*! - Returns uuid of an object, if present. - - This is the same as retrieving a value of the \c _uuid element. - - \sa setUuid() -*/ -QUuid JsonDbObject::uuid() const -{ - QVariant v = value(QLatin1String("_uuid")); - if (v.canConvert<QUuid>()) - return v.value<QUuid>(); - return QUuid(v.toString()); -} - -/*! - Inserts the given \a uuid into the map. - - This is the same as calling \c {insert(QLatin1String("_uuid"), uuid)}. - - \sa uuid(), uuidFromObject() -*/ -void JsonDbObject::setUuid(const QUuid &uuid) -{ - insert(QLatin1String("_uuid"), QVariant::fromValue(uuid)); -} - -/*! - Returns a new uuid that can be used to identify given \a object. - - Note that the returned uuid might be unique on every invocation on the same - object, if the \a object doesn't have the \c{_id} property and there is no - schema. -*/ -QUuid JsonDbObject::uuidFromObject(const QVariantMap &object) -{ - QString idvalue = object.value(QLatin1String("_id")).toString(); - if (idvalue.isNull()) - return QUuid::createUuid(); - return generateUUIDv3(idvalue); -} - -QT_END_NAMESPACE_JSONDB diff --git a/src/clientcompat/jsondb-object.h b/src/clientcompat/jsondb-object.h deleted file mode 100644 index 774f03e..0000000 --- a/src/clientcompat/jsondb-object.h +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDBOBJECT_H -#define JSONDBOBJECT_H - -#include <QtCore/qvariant.h> -#include <QtCore/quuid.h> - -#include "jsondb-global.h" - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE_JSONDB - -class Q_ADDON_JSONDB_EXPORT JsonDbObject : public QVariantMap -{ -public: - JsonDbObject(); - JsonDbObject(const QVariantMap &other); - - QUuid uuid() const; - void setUuid(const QUuid &uuid); - - static QUuid uuidFromObject(const QVariantMap &object); -}; - -QT_END_NAMESPACE_JSONDB - -QT_END_HEADER - -#endif // JSONDBOBJECT_H diff --git a/src/clientcompat/jsondb-oneshot.cpp b/src/clientcompat/jsondb-oneshot.cpp deleted file mode 100644 index a9a84a3..0000000 --- a/src/clientcompat/jsondb-oneshot.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "jsondb-oneshot_p.h" - -QT_BEGIN_NAMESPACE_JSONDB - -#include "moc_jsondb-oneshot_p.cpp" - -QT_END_NAMESPACE_JSONDB diff --git a/src/clientcompat/jsondb-oneshot_p.h b/src/clientcompat/jsondb-oneshot_p.h deleted file mode 100644 index 92794dd..0000000 --- a/src/clientcompat/jsondb-oneshot_p.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDB_ONESHOT_P_H -#define JSONDB_ONESHOT_P_H - -#include <QObject> -#include <QVariant> -#include <QDebug> -#include <QEventLoop> -#include <QThread> - -#include "jsondb-global.h" - -QT_BEGIN_NAMESPACE_JSONDB - -/*! - \internal - The one-shot class is strictly for the private use of the connection object -*/ -class JsonDbOneShot : public QObject -{ - Q_OBJECT - friend class JsonDbConnection; -public slots: - void handleResponse( int id, const QVariant& data ) { - if (id == mId) { emit response(data); deleteLater(); } - } - void handleError( int id, int code, const QString& message ) { - if (id == mId) { emit error(code, message); deleteLater(); } - } -signals: - void response(const QVariant& object); - void error(int code, const QString& message); -private: - int mId; -}; - -QT_END_NAMESPACE_JSONDB - -#endif // JSONDB_ONESHOT_P_H diff --git a/src/clientcompat/jsondb-query.cpp b/src/clientcompat/jsondb-query.cpp deleted file mode 100644 index f0678f7..0000000 --- a/src/clientcompat/jsondb-query.cpp +++ /dev/null @@ -1,714 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "jsondb-query.h" -#include "jsondb-client.h" -#include "jsondb-strings_p.h" - -QT_BEGIN_NAMESPACE_JSONDB - -/*! - \class JsonDbResultBase - \internal -*/ - -class JsonDbResultBasePrivate -{ - Q_DECLARE_PUBLIC(JsonDbResultBase) -public: - JsonDbResultBasePrivate(JsonDbClient *c, JsonDbResultBase *q) - : q_ptr(q), client(c), requestId(-1), isFinished(true) - { } - - JsonDbResultBase *q_ptr; - JsonDbClient *client; - - int requestId; - bool isFinished; - - QVariantMap header; - QVariantList results; - - QString partition; -}; - -class JsonDbQueryPrivate : public JsonDbResultBasePrivate -{ - Q_DECLARE_PUBLIC(JsonDbQuery) -public: - JsonDbQueryPrivate(JsonDbClient *c, JsonDbQuery *q) - : JsonDbResultBasePrivate(c, q), queryOffset(0), queryLimit(-1) - { } - - void _q_response(int reqId, const QVariant &); - void _q_error(int reqId, int code, const QString &message); - void _q_emitMoreData(); - - // HACK HACK HACK - QVariantList moreResults; - - QString query; - int queryOffset; - int queryLimit; - QMap<QString,QVariant> bindings; -}; - -void JsonDbQueryPrivate::_q_response(int reqId, const QVariant &response_) -{ - Q_UNUSED(reqId); - Q_Q(JsonDbQuery); - - QVariantMap response = response_.toMap(); - header = QVariantMap(); - header.insert(QLatin1String("state"), response.value(QLatin1String("state")).value<quint32>()); - header.insert(QLatin1String("sortKey"), response.value(QLatin1String("sortKey")).value<QString>()); - - emit q->started(); - - // to mimic future behavior with streaming / client-side reads split data into two chunks - QVariantList r = response.value(JsonDbString::kDataStr).toList(); - if (r.size()) { - int count = qMax((r.size() / 2), 1); - results = r.mid(0, count); - r.erase(r.begin(), r.begin() + count); - moreResults = r; - } - - if (!results.isEmpty()) { - emit q->resultsReady(results.size()); - QMetaObject::invokeMethod(q, "_q_emitMoreData", Qt::QueuedConnection); - } else { - emit q->finished(); - } -} - -void JsonDbQueryPrivate::_q_emitMoreData() -{ - Q_Q(JsonDbQuery); - results += moreResults; - moreResults = QVariantList(); - - isFinished = true; - - if (!results.isEmpty()) - emit q->resultsReady(results.size()); - emit q->finished(); -} - -void JsonDbQueryPrivate::_q_error(int reqId, int code, const QString &message) -{ - Q_UNUSED(reqId); - Q_Q(JsonDbQuery); - emit q->error(JsonDbError::ErrorCode(code), message); -} - -JsonDbResultBase::JsonDbResultBase(JsonDbResultBasePrivate *d, QObject *parent) - : QObject(parent), d_ptr(d) -{ - Q_ASSERT(d != 0); -} - -JsonDbResultBase::~JsonDbResultBase() -{ -} - -int JsonDbResultBase::requestId() const -{ - return d_func()->requestId; -} - -bool JsonDbResultBase::isFinished() const -{ - return d_func()->isFinished; -} - -QVariantMap JsonDbResultBase::header() const -{ - return d_func()->header; -} - -int JsonDbResultBase::resultsAvailable() const -{ - return d_func()->results.size(); -} - -QString JsonDbResultBase::partition() const -{ - return d_func()->partition; -} - -void JsonDbResultBase::setPartition(const QString &partition) -{ - Q_D(JsonDbResultBase); - d->partition = partition; -} - -QVariantList JsonDbResultBase::takeResults() -{ - Q_D(JsonDbResultBase); - QVariantList results; - results.swap(d->results); - return results; -} - -void JsonDbResultBase::start() -{ -} - -/*! - \class JsonDbQuery - - \brief The JsonDbQuery class allows to execute a given database query and - retrieve results. - - \code - #include <jsondb-client.h> - - QT_USE_NAMESPACE_JSONDB - - class QueryHandler : public QObject - { - Q_OBJECT - public: - QueryHandler() - { - JsonDbClient *client = new JsonDbClient(this); - JsonDbQuery *query = client->query(); - query->setQuery(QLatin1String("[?_type=\"Person\"]")); - QObject::connect(query, SIGNAL(resultsReady(int)), this, SLOT(onResultsReady(int))); - QObject::connect(query, SIGNAL(finished()), this, SLOT(onFinished())); - QObject::connect(query, SIGNAL(finished()), query, SLOT(deleteLater())); - query->start(); - } - - public slots: - void onResultsReady(int resultsAvailable) - { - qDebug() << "So far fetched" << resultsAvailable << "result(s)"; - } - void onFinished() - { - JsonDbQuery *query = qobject_cast<JsonDbQuery *>(sender()); - Q_ASSERT(query); - qDebug() << "Query complete, fetched" << query->resultsAvailable() << "result(s):"; - qDebug() << query->takeResults(); - } - }; - \endcode - - \sa JsonDbClient -*/ - -/*! - \property JsonDbQuery::partition - - Specifies the partition name the query operates on. -*/ - -/*! - \fn int JsonDbQuery::requestId() const - - Returns a request id for the query request. -*/ - -/*! - \fn bool JsonDbQuery::isFinished() const - - Returns true if the query is complete and the finished() signal was already - emitted. - - \sa finished() -*/ - -/*! - \fn void JsonDbQuery::started() - - Signal is emitted after the query execution was started and some initial - data is available. - - \sa start(), stateNumber, sortKey -*/ -/*! - \fn void JsonDbQuery::resultsReady(int resultsAvailable) - - Signal is emitted after you start() a query and there are new results - available that match it. \a resultsAvailable tells you how many results are - available at this point, and you can retrieve them with takeResults(). - - \sa finished(), takeResults() -*/ -/*! - \fn void JsonDbQuery::finished() - - Signal is emitted after the query is complete. - - \sa takeResults(), resultsReady(), isFinished(), started() -*/ -/*! - \fn void JsonDbQuery::error(JsonDbError::ErrorCode code, const QString &message) - - Signal is emitted when an error with a given \a code occured while - executing a query. Extended information about the error can be retrieved - from \a message. -*/ -/*! - \fn QVariantList JsonDbQuery::takeResults() - - Returns the results of the query that are retrieved so far and clears the - internal result list. - - Unless the results are "taken", they are accumulated on every resultsReady() - signal, so there is no need to "take" data before finished() signal is - emitted unless you want to process results in chunks. - - \sa resultsReady(), finished() -*/ -/*! - \property JsonDbQuery::resultsAvailable - - Returns the amount of results of the query that are accumulated so far. - - \sa takeResults(), resultsReady(), isFinished() -*/ - -/*! - \internal -*/ -JsonDbQuery::JsonDbQuery(JsonDbClient *client, QObject *parent) - : JsonDbResultBase(new JsonDbQueryPrivate(client, this), parent) -{ - Q_ASSERT(client); -} - -/*! - Destroys the object. -*/ -JsonDbQuery::~JsonDbQuery() -{ -} - -/*! - \property JsonDbQuery::stateNumber - - Returns a database state number that the query was executed on. - - The property is populated after started() signal was emitted. - - \sa started() -*/ -quint32 JsonDbQuery::stateNumber() const -{ - return d_func()->header.value(QLatin1String("state"), quint32(0)).value<quint32>(); -} - -/*! - \property JsonDbQuery::sortKey - - Returns a field that was used as a sort key when executing a query. - - The results of the query are ordered by that field. - - The property is populated after started() signal was emitted. - - \sa started(), takeResults() -*/ -QString JsonDbQuery::sortKey() const -{ - return d_func()->header.value(QLatin1String("sortKey")).value<QString>(); -} - -/*! - \property JsonDbQuery::query - - \brief the query string - - Set this property to the query string that you want to execute. - - \sa queryOffset, queryLimit, start(), bindValue() -*/ -QString JsonDbQuery::query() const -{ - return d_func()->query; -} - -void JsonDbQuery::setQuery(const QString &query) -{ - Q_D(JsonDbQuery); - d->query = query; -} - -/*! - \property JsonDbQuery::queryOffset - - \brief the initial offset of a query - - Set this property to the numeric value from which the results will be returned. - - \sa query, queryLimit, start() -*/ -int JsonDbQuery::queryOffset() const -{ - return d_func()->queryOffset; -} - -void JsonDbQuery::setQueryOffset(int offset) -{ - Q_D(JsonDbQuery); - d->queryOffset = offset; -} - -/*! - \property JsonDbQuery::queryLimit - - \brief the limit of a query - - This property defines how many results will be retrieved at most. - - \sa query, queryOffset, start() -*/ -int JsonDbQuery::queryLimit() const -{ - return d_func()->queryLimit; -} - -void JsonDbQuery::setQueryLimit(int limit) -{ - Q_D(JsonDbQuery); - d->queryLimit = limit; -} - -/*! - \fn void JsonDbQuery::start() - - Starts the query. - - \sa query, queryLimit, started(), resultsReady(), finished() -*/ -void JsonDbQuery::start() -{ - Q_D(JsonDbQuery); - d->isFinished = false; - d->requestId = d->client->query(d->query, d->queryOffset, d->queryLimit, d->bindings, d->partition, - this, SLOT(_q_response(int,QVariant)), SLOT(_q_error(int,int,QString))); -} - -/*! - \fn void JsonDbQuery::bindValue(const QString &placeHolder, const QVariant &val) - - Set the placeholder \a placeHolder to be bound to value \a val in the query - string. Note that '%' is the only placeholder mark supported by the query. - The marker '%' should not be included in the \a placeHolder name. - - \code - JsonDbQuery *query = jsonDbClient->query(); - query->setQuery(QLatin1String("[?_type=\"Person\"][?firstName = %name]")); - query->bindValue(QLatin1String("name"), QLatin1String("Malcolm")); - \endcode - - \sa query, boundValue(), boundValues() -*/ -void JsonDbQuery::bindValue(const QString &placeHolder, const QVariant &val) -{ - Q_D(JsonDbQuery); - d->bindings.insert(placeHolder, val); -} - -/*! - \fn QVariant JsonDbQuery::boundValue(const QString &placeHolder) const - - Returns the value for the \a placeHolder. -*/ -QVariant JsonDbQuery::boundValue(const QString &placeHolder) const -{ - return d_func()->bindings.value(placeHolder); -} - -/*! - \fn QMap<QString,QVariant> JsonDbQuery::boundValues() const - - Returns a map of the bound values -*/ -QMap<QString,QVariant> JsonDbQuery::boundValues() const -{ - return d_func()->bindings; -} - -/*! - \class JsonDbChangesSince - - \brief The JsonDbChangesSince class allows to retrieve history of changes - to objects in a database. - - \sa JsonDbClient -*/ - -/*! - \property JsonDbChangesSince::partition - - Specifies the partition name the request operates on. -*/ - -/*! - \fn int JsonDbChangesSince::requestId() const - - Returns a request id for the "changes since" request. -*/ - -/*! - \fn bool JsonDbChangesSince::isFinished() const - - Returns true if the request is complete and the finished() signal was - already emitted. - - \sa finished() -*/ - -/*! - \fn void JsonDbChangesSince::started() - - Signal is emitted after the request execution was started and some initial - data is available. - - \sa start(), startingStateNumber, currentStateNumber -*/ -/*! - \fn void JsonDbChangesSince::resultsReady(int resultsAvailable) - - Signal is emitted after you start() a request and there are new results - available that match it. \a resultsAvailable tells you how many results are - available at this point, and you can retrieve them with takeResults(). - - \sa finished(), takeResults() -*/ -/*! - \fn void JsonDbChangesSince::finished() - - Signal is emitted after the request is complete. - - \sa takeResults(), resultsReady(), isFinished(), started() -*/ -/*! - \fn void JsonDbChangesSince::error(JsonDbError::ErrorCode code, const QString &message) - - Signal is emitted when an error with a given \a code occured while - executing a request. Extended information about the error can be retrieved - from \a message. -*/ -/*! - \fn QVariantList JsonDbChangesSince::takeResults() - - Returns the results of the request that are retrieved so far and clears the - internal result list. - - Unless the results are "taken", they are accumulated on every resultsReady() - signal, so there is no need to "take" data before finished() signal is - emitted unless you want to process results in chunks. - - \sa resultsReady(), finished() -*/ -/*! - \property JsonDbChangesSince::resultsAvailable - - Returns the amount of results of the request that are accumulated so far. - - \sa takeResults(), resultsReady(), isFinished() -*/ - -class JsonDbChangesSincePrivate : public JsonDbResultBasePrivate -{ - Q_DECLARE_PUBLIC(JsonDbChangesSince) -public: - JsonDbChangesSincePrivate(JsonDbClient *c, JsonDbChangesSince *q) - : JsonDbResultBasePrivate(c, q), stateNumber(0) - { } - - void _q_response(int reqId, const QVariant &); - void _q_error(int reqId, int code, const QString &message); - void _q_emitMoreData(); - - // HACK HACK HACK - QVariantList moreResults; - - QStringList types; - quint32 stateNumber; -}; - -void JsonDbChangesSincePrivate::_q_response(int reqId, const QVariant &response_) -{ - Q_UNUSED(reqId); - Q_Q(JsonDbChangesSince); - - QVariantMap response = response_.toMap(); - header = QVariantMap(); - header.insert(QLatin1String("startingStateNumber"), response.value(QLatin1String("startingStateNumber")).value<quint32>()); - header.insert(QLatin1String("currentStateNumber"), response.value(QLatin1String("currentStateNumber")).value<quint32>()); - - emit q->started(); - - // to mimic future behavior with streaming / client-side reads split data into two chunks - QVariantList r = response.value(QLatin1String("changes")).toList(); - int count = r.size() / 2; - results = r.mid(0, count); - r.erase(r.begin(), r.begin() + count); - moreResults = r; - - emit q->resultsReady(results.size()); - QMetaObject::invokeMethod(q, "_q_emitMoreData", Qt::QueuedConnection); -} - -void JsonDbChangesSincePrivate::_q_emitMoreData() -{ - Q_Q(JsonDbChangesSince); - results += moreResults; - moreResults = QVariantList(); - - isFinished = true; - - if (!results.isEmpty()) - emit q->resultsReady(results.size()); - emit q->finished(); -} - -void JsonDbChangesSincePrivate::_q_error(int reqId, int code, const QString &message) -{ - Q_UNUSED(reqId); - Q_Q(JsonDbChangesSince); - emit q->error(JsonDbError::ErrorCode(code), message); -} - -/*! - \internal -*/ -JsonDbChangesSince::JsonDbChangesSince(JsonDbClient *client, QObject *parent) - : JsonDbResultBase(new JsonDbChangesSincePrivate(client, this), parent) -{ - Q_ASSERT(client); -} - -/*! - Destroys the object. -*/ -JsonDbChangesSince::~JsonDbChangesSince() -{ -} - -/*! - \property JsonDbChangesSince::startingStateNumber - - Returns the starting state number for the changesSince request. - - The property is populated after started() signal was emitted. - - \sa started() -*/ -quint32 JsonDbChangesSince::startingStateNumber() const -{ - return d_func()->header.value(QLatin1String("startingStateNumber"), quint32(0)).value<quint32>(); -} - -/*! - \property JsonDbChangesSince::currentStateNumber - - Returns the ending state number for the changesSince request. - - The property is populated after started() signal was emitted. - - \sa started() -*/ -quint32 JsonDbChangesSince::currentStateNumber() const -{ - return d_func()->header.value(QLatin1String("currentStateNumber"), quint32(0)).value<quint32>(); -} - -/*! - \property JsonDbChangesSince::types - - \brief the list of object types for which we return changes - - \sa stateNumber, start() -*/ -QStringList JsonDbChangesSince::types() const -{ - return d_func()->types; -} - -void JsonDbChangesSince::setTypes(const QStringList &types) -{ - Q_D(JsonDbChangesSince); - d->types = types; -} - -/*! - \property JsonDbChangesSince::stateNumber - - \brief the initial state number from which changes should be retrieved. - - \sa types, start() -*/ -quint32 JsonDbChangesSince::stateNumber() const -{ - return d_func()->stateNumber; -} - -void JsonDbChangesSince::setStateNumber(quint32 stateNumber) -{ - Q_D(JsonDbChangesSince); - d->stateNumber = stateNumber; -} - -/*! - \fn void JsonDbChangesSince::start() - - Starts the "changes since" request. - - \sa stateNumber, types, started(), resultsReady(), finished() -*/ -void JsonDbChangesSince::start() -{ - Q_D(JsonDbChangesSince); - d->isFinished = false; - d->requestId = d->client->changesSince(d->stateNumber, d->types, d->partition, - this, SLOT(_q_response(int,QVariant)), SLOT(_q_error(int,int,QString))); -} - -#include "moc_jsondb-query.cpp" - -QT_END_NAMESPACE_JSONDB diff --git a/src/clientcompat/jsondb-query.h b/src/clientcompat/jsondb-query.h deleted file mode 100644 index 5e42105..0000000 --- a/src/clientcompat/jsondb-query.h +++ /dev/null @@ -1,214 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDB_QUERY_H -#define JSONDB_QUERY_H - -#include <QObject> -#include <QVariantMap> -#include <QList> -#include <QStringList> -#include <QScopedPointer> - -#include "jsondb-global.h" -#include "jsondb-error.h" - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE_JSONDB - -class JsonDbClient; -class JsonDbResultBasePrivate; -class JsonDbQueryPrivate; -class JsonDbChangesSincePrivate; - -class Q_ADDON_JSONDB_EXPORT JsonDbResultBase : public QObject -{ - Q_OBJECT - Q_PROPERTY(int requestId READ requestId) - Q_PROPERTY(bool isFinished READ isFinished) - Q_PROPERTY(int resultsAvailable READ resultsAvailable) - Q_PROPERTY(QString partition READ partition WRITE setPartition) - -public: - ~JsonDbResultBase(); - - int requestId() const; - bool isFinished() const; - - QVariantMap header() const; - - int resultsAvailable() const; - - QString partition() const; - void setPartition(const QString &); - -public Q_SLOTS: - virtual void start(); - QVariantList takeResults(); - -Q_SIGNALS: - void started(); - void resultsReady(int resultsAvailable); - void finished(); -#ifdef qdoc - void error(JsonDbError::ErrorCode code, const QString &message); -#else - void error(QtAddOn::JsonDb::JsonDbError::ErrorCode code, const QString &message); -#endif - -protected: - JsonDbResultBase(JsonDbResultBasePrivate *d, QObject *parent = 0); - - Q_DISABLE_COPY(JsonDbResultBase) - Q_DECLARE_PRIVATE(JsonDbResultBase) - QScopedPointer<JsonDbResultBasePrivate> d_ptr; -}; - -class Q_ADDON_JSONDB_EXPORT JsonDbQuery : public JsonDbResultBase -{ - Q_OBJECT - Q_PROPERTY(QString partition READ partition WRITE setPartition) - Q_PROPERTY(QString query READ query WRITE setQuery) - Q_PROPERTY(int queryOffset READ queryOffset WRITE setQueryOffset) - Q_PROPERTY(int queryLimit READ queryLimit WRITE setQueryLimit) - Q_PROPERTY(int resultsAvailable READ resultsAvailable) - - Q_PROPERTY(quint32 stateNumber READ stateNumber) - Q_PROPERTY(QString sortKey READ sortKey) - -public: - ~JsonDbQuery(); - - quint32 stateNumber() const; - QString sortKey() const; - - QString query() const; - void setQuery(const QString &); - - int queryOffset() const; - void setQueryOffset(int offset); - - int queryLimit() const; - void setQueryLimit(int limit); - -#ifdef qdoc - int requestId() const; - bool isFinished() const; -Q_SIGNALS: - void started(); - void resultsReady(int resultsAvailable); - void finished(); - void error(JsonDbError::ErrorCode code, const QString &message); -public Q_SLOTS: - QVariantList takeResults(); -#endif - -public Q_SLOTS: - virtual void start(); - - void bindValue(const QString &placeHolder, const QVariant &val); - QVariant boundValue(const QString &placeHolder) const; - QMap<QString,QVariant> boundValues() const; - -private: - JsonDbQuery(JsonDbClient *client, QObject *parent = 0); - - Q_DECLARE_PRIVATE(JsonDbQuery) - Q_PRIVATE_SLOT(d_func(), void _q_response(int,QVariant)) - Q_PRIVATE_SLOT(d_func(), void _q_error(int,int,QString)) - Q_PRIVATE_SLOT(d_func(), void _q_emitMoreData()) - friend class JsonDbClient; -}; - -class Q_ADDON_JSONDB_EXPORT JsonDbChangesSince : public JsonDbResultBase -{ - Q_OBJECT - Q_PROPERTY(QString partition READ partition WRITE setPartition) - Q_PROPERTY(QStringList types READ types WRITE setTypes) - Q_PROPERTY(quint32 stateNumber READ stateNumber WRITE setStateNumber) - Q_PROPERTY(int resultsAvailable READ resultsAvailable) - - Q_PROPERTY(quint32 startingStateNumber READ startingStateNumber) - Q_PROPERTY(quint32 currentStateNumber READ currentStateNumber) - -public: - ~JsonDbChangesSince(); - - quint32 startingStateNumber() const; - quint32 currentStateNumber() const; - - QStringList types() const; - void setTypes(const QStringList &types); - - quint32 stateNumber() const; - void setStateNumber(quint32 stateNumber); - -#ifdef qdoc - int requestId() const; - bool isFinished() const; -Q_SIGNALS: - void started(); - void resultsReady(int resultsAvailable); - void finished(); - void error(JsonDbError::ErrorCode code, const QString &message); -public Q_SLOTS: - QVariantList takeResults(); -#endif - -public Q_SLOTS: - virtual void start(); - -private: - JsonDbChangesSince(JsonDbClient *client, QObject *parent = 0); - - Q_DECLARE_PRIVATE(JsonDbChangesSince) - Q_PRIVATE_SLOT(d_func(), void _q_response(int,QVariant)) - Q_PRIVATE_SLOT(d_func(), void _q_error(int,int,QString)) - Q_PRIVATE_SLOT(d_func(), void _q_emitMoreData()) - friend class JsonDbClient; -}; - -QT_END_NAMESPACE_JSONDB - -QT_END_HEADER - -#endif // JSONDB_QUERY_H diff --git a/src/clientcompat/jsondb-strings.cpp b/src/clientcompat/jsondb-strings.cpp deleted file mode 100644 index 7e31a6f..0000000 --- a/src/clientcompat/jsondb-strings.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "jsondb-strings_p.h" - -QT_BEGIN_NAMESPACE_JSONDB - -const QString JsonDbString::kUuidStr = QString::fromLatin1("_uuid"); -const QString JsonDbString::kVersionStr = QString::fromLatin1("_version"); -const QString JsonDbString::kIdStr = QString::fromLatin1("id"); -const QString JsonDbString::kResultStr = QString::fromLatin1("result"); -const QString JsonDbString::kErrorStr = QString::fromLatin1("error"); -const QString JsonDbString::kFieldNameStr = QString::fromLatin1("fieldName"); -const QString JsonDbString::kCodeStr = QString::fromLatin1("code"); -const QString JsonDbString::kMessageStr = QString::fromLatin1("message"); -const QString JsonDbString::kNameStr = QString::fromLatin1("name"); -const QString JsonDbString::kCountStr = QString::fromLatin1("count"); -const QString JsonDbString::kCurrentStr = QString::fromLatin1("_current"); -const QString JsonDbString::kDomainStr = QString::fromLatin1("_domain"); -const QString JsonDbString::kOwnerStr = QString::fromLatin1("_owner"); -const QString JsonDbString::kTypeStr = QString::fromLatin1("_type"); -const QString JsonDbString::kTypesStr = QString::fromLatin1("types"); -const QString JsonDbString::kParentStr = QString::fromLatin1("_parent"); -const QString JsonDbString::kSchemaTypeStr = QString::fromLatin1("_schemaType"); - -const QString JsonDbString::kActionStr = QString::fromLatin1("action"); -const QString JsonDbString::kActionsStr = QString::fromLatin1("actions"); -const QString JsonDbString::kActiveStr = QString::fromLatin1("active"); -const QString JsonDbString::kAddIndexStr = QString::fromLatin1("addIndex"); -const QString JsonDbString::kCreateStr = QString::fromLatin1("create"); -const QString JsonDbString::kDropStr = QString::fromLatin1("drop"); -const QString JsonDbString::kConflictsStr = QString::fromLatin1("conflicts"); -const QString JsonDbString::kConnectStr = QString::fromLatin1("connect"); -const QString JsonDbString::kDataStr = QString::fromLatin1("data"); -const QString JsonDbString::kDeletedStr = QString::fromLatin1("_deleted"); -const QString JsonDbString::kDisconnectStr = QString::fromLatin1("disconnect"); -const QString JsonDbString::kExplanationStr = QString::fromLatin1("explanation"); -const QString JsonDbString::kFindStr = QString::fromLatin1("find"); -const QString JsonDbString::kLengthStr = QString::fromLatin1("length"); -const QString JsonDbString::kLimitStr = QString::fromLatin1("limit"); -const QString JsonDbString::kMapTypeStr = QString::fromLatin1("Map"); -const QString JsonDbString::kMetaStr = QString::fromLatin1("_meta"); -const QString JsonDbString::kNotifyStr = QString::fromLatin1("notify"); -const QString JsonDbString::kNotificationTypeStr = QString::fromLatin1("notification"); -const QString JsonDbString::kObjectStr = QString::fromLatin1("object"); -const QString JsonDbString::kOffsetStr = QString::fromLatin1("offset"); -const QString JsonDbString::kQueryStr = QString::fromLatin1("query"); -const QString JsonDbString::kReduceTypeStr = QString::fromLatin1("Reduce"); -const QString JsonDbString::kRemoveStr = QString::fromLatin1("remove"); -const QString JsonDbString::kSchemaStr = QString::fromLatin1("schema"); -const QString JsonDbString::kUpdateStr = QString::fromLatin1("update"); -const QString JsonDbString::kTokenStr = QString::fromLatin1("token"); -const QString JsonDbString::kFlushStr = QString::fromLatin1("flush"); -const QString JsonDbString::kSettingsStr = QString::fromLatin1("settings"); -const QString JsonDbString::kViewTypeStr = QString::fromLatin1("View"); -const QString JsonDbString::kChangesSinceStr = QString::fromLatin1("changesSince"); -const QString JsonDbString::kStateNumberStr = QString::fromLatin1("stateNumber"); -const QString JsonDbString::kCollapsedStr = QString::fromLatin1("collapsed"); -const QString JsonDbString::kCurrentStateNumberStr = QString::fromLatin1("currentStateNumber"); -const QString JsonDbString::kStartingStateNumberStr = QString::fromLatin1("startingStateNumber"); -const QString JsonDbString::kTombstoneStr = QString::fromLatin1("Tombstone"); -const QString JsonDbString::kPartitionTypeStr = QString::fromLatin1("Partition"); -const QString JsonDbString::kPartitionStr = QString::fromLatin1("partition"); -const QString JsonDbString::kLogStr = QString::fromLatin1("log"); -const QString JsonDbString::kPropertyNameStr = QString::fromLatin1("propertyName"); -const QString JsonDbString::kPropertyTypeStr = QString::fromLatin1("propertyType"); -const QString JsonDbString::kPropertyFunctionStr = QString::fromLatin1("propertyFunction"); -const QString JsonDbString::kObjectTypeStr = QString::fromLatin1("objectType"); -const QString JsonDbString::kDbidTypeStr = QString::fromLatin1("DatabaseId"); -const QString JsonDbString::kIndexTypeStr = QString::fromLatin1("Index"); -const QString JsonDbString::kLocaleStr = QString::fromLatin1("locale"); -const QString JsonDbString::kCollationStr = QString::fromLatin1("collation"); -const QString JsonDbString::kCaseSensitiveStr = QString::fromLatin1("caseSensitive"); -const QString JsonDbString::kCasePreferenceStr = QString::fromLatin1("casePreference"); -const QString JsonDbString::kDatabaseSchemaVersionStr = QString::fromLatin1("databaseSchemaVersion"); -const QString JsonDbString::kPathStr = QString::fromLatin1("path"); -const QString JsonDbString::kDefaultStr = QString::fromLatin1("default"); - -QT_END_NAMESPACE_JSONDB diff --git a/src/clientcompat/jsondb-strings_p.h b/src/clientcompat/jsondb-strings_p.h deleted file mode 100644 index 16258d8..0000000 --- a/src/clientcompat/jsondb-strings_p.h +++ /dev/null @@ -1,126 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDB_STRINGS_H -#define JSONDB_STRINGS_H - -#include <QString> -#include "jsondb-global.h" - -QT_BEGIN_NAMESPACE_JSONDB - -class Q_ADDON_JSONDB_EXPORT JsonDbString { -public: - static const QString kActionStr; - static const QString kActionsStr; - static const QString kActiveStr; - static const QString kAddIndexStr; - static const QString kCodeStr; - static const QString kConflictsStr; - static const QString kConnectStr; - static const QString kCountStr; - static const QString kCreateStr; - static const QString kDropStr; - static const QString kCurrentStr; - static const QString kDataStr; - static const QString kDeletedStr; - static const QString kDisconnectStr; - static const QString kDomainStr; - static const QString kErrorStr; - static const QString kExplanationStr; - static const QString kFieldNameStr; - static const QString kFindStr; - static const QString kNameStr; - static const QString kIdStr; - static const QString kIndexValueStr; - static const QString kLengthStr; - static const QString kLimitStr; - static const QString kMapTypeStr; - static const QString kMessageStr; - static const QString kMetaStr; - static const QString kNotifyStr; - static const QString kNotificationTypeStr; - static const QString kObjectStr; - static const QString kParentStr; - static const QString kOffsetStr; - static const QString kOwnerStr; - static const QString kQueryStr; - static const QString kReduceTypeStr; - static const QString kRemoveStr; - static const QString kResultStr; - static const QString kSchemaStr; - static const QString kSchemaTypeStr; - static const QString kTypeStr; - static const QString kTypesStr; - static const QString kUpdateStr; - static const QString kUuidStr; - static const QString kVersionStr; - static const QString kViewTypeStr; - static const QString kTokenStr; - static const QString kFlushStr; - static const QString kSettingsStr; - static const QString kChangesSinceStr; - static const QString kStateNumberStr; - static const QString kCollapsedStr; - static const QString kCurrentStateNumberStr; - static const QString kStartingStateNumberStr; - static const QString kTombstoneStr; - static const QString kPartitionTypeStr; - static const QString kPartitionStr; - static const QString kLogStr; - static const QString kPropertyNameStr; - static const QString kPropertyTypeStr; - static const QString kPropertyFunctionStr; - static const QString kObjectTypeStr; - static const QString kDbidTypeStr; - static const QString kIndexTypeStr; - static const QString kLocaleStr; - static const QString kCollationStr; - static const QString kCaseSensitiveStr; - static const QString kCasePreferenceStr; - static const QString kDatabaseSchemaVersionStr; - static const QString kPathStr; - static const QString kDefaultStr; -}; - -QT_END_NAMESPACE_JSONDB - -#endif /* JSONDB-STRINGS_H */ diff --git a/src/imports/imports.pro b/src/imports/imports.pro index c28b9e3..20fef9c 100644 --- a/src/imports/imports.pro +++ b/src/imports/imports.pro @@ -1,3 +1,3 @@ TEMPLATE = subdirs -SUBDIRS += jsondb-listmodel jsondb +SUBDIRS += jsondb diff --git a/src/imports/jsondb-listmodel/jsondb-component.cpp b/src/imports/jsondb-listmodel/jsondb-component.cpp deleted file mode 100644 index 03406bc..0000000 --- a/src/imports/jsondb-listmodel/jsondb-component.cpp +++ /dev/null @@ -1,434 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QDebug> -#include <QJSEngine> - -#include "jsondb-component.h" -#include "private/jsondb-strings_p.h" -#include "jsondb-client.h" - -JsonDbNotificationComponent::JsonDbNotificationComponent(JsonDbComponent *repo) - : QObject(repo) - , mId(-1) -{ -} - -JsonDbNotificationComponent::~JsonDbNotificationComponent() -{ - remove(); -} - -void JsonDbNotificationComponent::remove() -{ - if (!mUuid.isEmpty()) - emit removed(mUuid); // the JsonDbComponent connects to this and does the real work. - else - emit removed(mId); -} - -JsonDbNotificationHandle::JsonDbNotificationHandle(JsonDbNotificationComponent *notification) - : QObject(notification) - , mNotification(notification) -{ -} - -JsonDbNotificationHandle::~JsonDbNotificationHandle() -{ -} - -QString JsonDbNotificationHandle::uuid() const -{ - if (mNotification.isNull()) - return QString(); - else - return mNotification->mUuid; -} - -void JsonDbNotificationHandle::remove() -{ - if (!mNotification.isNull()) - mNotification->remove(); -} - -/*! - \qmltype JsonDbComponent - \instantiates JsonDbComponent - \inqmlmodule QtAddOn.JsonDb 1.0 - \since 1.0 - - The JsonDb element allows you find, create, update, or remove objects from JsonDb. - Most of the functions take script objects as parameters. - Those can have different values "query", "limit" and "offset" - - Most of the functions take optional success and error callback functions. Those script - functions are called in case of an error (or succes) -*/ - -JsonDbComponent::JsonDbComponent(QObject *parent) - : QObject(parent) - , mDebugOutput(false) - , mJsonDb(new JsonDbClient(this)) -{ - connect(mJsonDb, SIGNAL(response(int,QVariant)), - this, SLOT(jsonDbResponse(int,QVariant)), - Qt::QueuedConnection); - connect(mJsonDb, SIGNAL(error(int,int,QString)), - this, SLOT(jsonDbErrorResponse(int,int,QString)), - Qt::QueuedConnection); - connect(mJsonDb, SIGNAL(notified(QString,QVariant,QString)), - this, SLOT(jsonDbNotified(QString,QVariant,QString)), - Qt::QueuedConnection); -} - -JsonDbComponent::~JsonDbComponent() -{ -} - -/*! - \qmlsignal QtAddOn.JsonDb::JsonDb::onResponse() - - This handler is called when the database responds to a request. -*/ - -/*! - \qmlsignal QtAddOn.JsonDb::JsonDb::onError() - - This handler is called when there is an error in a database request. -*/ - -/*! - \qmlmethod QtAddOn.JsonDb::JsonDb::create(object) - - Creates the \a object in the database. - The \a object must not have a "_uuid" field. - On success, emits the response signal. - Returns the request uuid. -*/ -int JsonDbComponent::create(const QJSValue &object, - const QJSValue &successCallback, - const QJSValue &errorCallback) -{ - if (mDebugOutput) - qDebug() << "[JSONDB] create:"<<object.toString(); - - return addRequestInfo(mJsonDb->create(object.toVariant()), JsonDbComponent::Create, object, successCallback, errorCallback); -} - -/*! - \qmlmethod QtAddOn.JsonDb::JsonDb::update(object queryObject, object successFunction, object errorFunction) - - Updates the database to match the new object. - The \a object must have a valid "uuid" field. - On success, emits the response signal. - Returns the request uuid. - */ -int JsonDbComponent::update(const QJSValue &object, - const QJSValue &successCallback, - const QJSValue &errorCallback) -{ - return addRequestInfo(mJsonDb->update(object.toVariant()), JsonDbComponent::Update, object, successCallback, errorCallback); -} - -/*! - \qmlmethod QtAddOn.JsonDb::JsonDb::remove(object queryObject, object successFunction, object errorFunction) - - Removes the object from the database. - The \a object must have a valid "uuid" field. - On success, emits the response signal. - Returns the request uuid. - */ -int JsonDbComponent::remove(const QJSValue &object, - const QJSValue &successCallback, - const QJSValue &errorCallback) -{ - if (mDebugOutput) - qDebug() << "[JSONDB] remove:"<<object.toString(); - - return addRequestInfo(mJsonDb->remove(object.toVariant()), JsonDbComponent::Remove, object, successCallback, errorCallback); -} - -/*! - \qmlmethod QtAddOn.JsonDb::JsonDb::find(string query, int limit, int offset) - - Takes a JsonQuery string, a limit, and an offset, and issues a query to the database. - Returns the request uuid. - */ -int JsonDbComponent::find(const QJSValue &object, - const QJSValue &successCallback, - const QJSValue &errorCallback) -{ - if (mDebugOutput) - qDebug() << "[JSONDB] find:"<<object.toString(); - - return addRequestInfo(mJsonDb->find(object.toVariant()), JsonDbComponent::Find, object, successCallback, errorCallback); -} - -/*! - \qmlmethod QtAddOn.JsonDb::JsonDb::query(string query) - - Takes a JsonQuery string and issues a query to the database. - This function is a simple find function with no limit. -*/ -int JsonDbComponent::query(const QJSValue &object, - const QJSValue &successCallback, - const QJSValue &errorCallback) -{ - if (object.isString()) { - QJSValue request = object.engine()->newObject(); - request.setProperty(JsonDbString::kQueryStr, object); - request.setProperty(JsonDbString::kLimitStr, -1); - request.setProperty(JsonDbString::kOffsetStr, 0); - return find(request, successCallback, errorCallback); - } - - return find(object, successCallback, errorCallback); -} - -/*! - \qmlmethod QtAddOn.JsonDb::JsonDb::notification(object query, object actions, object callbackFunction, object errorFunction) - - Takes a JsonQuery string and creates a notification object from it. - The callbackFunction will called every time the notification is triggered. - The errorFunction is called if the creation of the notification fails. -*/ -QJSValue JsonDbComponent::notification(const QJSValue &object, - const QJSValue &actions, - const QJSValue &callback, - QJSValue errorCallback) -{ - // -- refuse to create notification without callback - if (!callback.isCallable()) { - qWarning() << "Refusing to create notification without callback."; - if (errorCallback.isCallable()) { - QJSValueList args; - errorCallback.call(args); - } - return QJSValue(); - } - - if (mDebugOutput) - qDebug() << "[JSONDB] notification:"<<object.toString(); - - int id; - - if (object.isString()) { - QJSValue request = object.engine()->newObject(); - request.setProperty(JsonDbString::kQueryStr, object); - request.setProperty(JsonDbString::kTypeStr, - JsonDbString::kNotificationTypeStr); - request.setProperty(JsonDbString::kActionsStr, actions); - - id = addRequestInfo(mJsonDb->create(request.toVariant()), JsonDbComponent::Notification, object, QJSValue(QJSValue::UndefinedValue), errorCallback); - - } else { - id = addRequestInfo(mJsonDb->create(object.toVariant()), JsonDbComponent::Notification, object, QJSValue(QJSValue::UndefinedValue), errorCallback); - } - - if (id <= 0) - return QJSValue(); - - // -- create notification object - JsonDbNotificationComponent* notification = new JsonDbNotificationComponent(this); - notification->mId = id; - notification->mCallback = callback; - mPendingNotifications.insert(id, notification); - - connect(notification, SIGNAL(removed(int)), - this, SLOT(notificationRemoved(int)), - Qt::QueuedConnection); - connect(notification, SIGNAL(removed(QString)), - this, SLOT(notificationRemoved(QString)), - Qt::QueuedConnection); - - JsonDbNotificationHandle *handle = new JsonDbNotificationHandle(notification); - return callback.engine()->newQObject(handle); -} - - -void JsonDbComponent::jsonDbResponse(int id, const QVariant &result) -{ - if (mRequests.contains(id)) { - JsonDbComponent::RequestInfo &info = mRequests[id]; - - QJSEngine *engine = info.object.engine(); - QJSValue scriptResult = engine->toScriptValue(result); - if (!scriptResult.property(JsonDbString::kUuidStr).isUndefined()) - info.object.setProperty(JsonDbString::kUuidStr, scriptResult.property(JsonDbString::kUuidStr)); - if (!scriptResult.property(JsonDbString::kVersionStr).isUndefined()) - info.object.setProperty(JsonDbString::kVersionStr, scriptResult.property(JsonDbString::kVersionStr)); - if (!scriptResult.property(JsonDbString::kOwnerStr).isUndefined()) - info.object.setProperty(JsonDbString::kOwnerStr, scriptResult.property(JsonDbString::kOwnerStr)); - - emit response(scriptResult, id); - - if (mDebugOutput) - qDebug() << "[JSONDB] response:" << scriptResult.toString(); - - // -- creating the notification object was successful - if (info.type == JsonDbComponent::Notification) { - if (mDebugOutput) - qDebug() << "successful created notification with" << scriptResult.property(JsonDbString::kUuidStr).toString(); - - // -- finish the notification with the new uuid - JsonDbNotificationComponent* notification = mPendingNotifications.take(id); - if (notification) { - // - if the removal was requested before the actual success: - // note: at this state the notification object is already deleted - if (mKilledNotifications.contains(id)) { - if (mDebugOutput) - qDebug() << "[JSONDB] kill notification again"; - notificationRemoved(scriptResult.property(JsonDbString::kUuidStr).toString()); // remove it again - mKilledNotifications.remove(id); - - } else { - notification->mId = -1; - notification->mUuid = scriptResult.property(JsonDbString::kUuidStr).toString(); - if (mDebugOutput) - qDebug() << "finish notification"<<notification->mUuid; - mNotifications.insert(notification->mUuid, notification); - } - - } else { - qWarning() << "Got response for notification that is not pending"; - } - } - - if (mDebugOutput) - qDebug() << "[JSONDB] response:" << scriptResult.toString(); - - // -- call the success callback function - if (info.successCallback.isCallable()) { - QJSValueList args; - args << scriptResult << info.successCallback.engine()->toScriptValue(id); - info.successCallback.call(args); - } - - mRequests.remove(id); - } -} -void JsonDbComponent::jsonDbErrorResponse(int id, int code, const QString& message) -{ - Q_UNUSED(code); - - if (mRequests.contains(id)) { - JsonDbComponent::RequestInfo &info = mRequests[id]; - - emit error(message, id); - - if (mDebugOutput) - qDebug() << "[JSONDB] error:" << message; - - if (info.type == JsonDbComponent::Notification) { - // -- creating the notification object was successful - qWarning() << "failed to create notification"; - mPendingNotifications.remove(id); - } - - // -- call the error callback function - if (info.errorCallback.isCallable()) { - QJSValueList args; - args << info.errorCallback.engine()->toScriptValue(message); - args << info.errorCallback.engine()->toScriptValue(code); - args << info.errorCallback.engine()->toScriptValue(id); - info.errorCallback.call(args); - } - - mRequests.remove(id); - } -} - -void JsonDbComponent::jsonDbNotified(const QString& notify_uuid, const QVariant& object, const QString& action) -{ - JsonDbNotificationComponent* notification = mNotifications.value(notify_uuid); - if (notification) { - QJSValueList args; - args << notification->mCallback.engine()->toScriptValue(object); - args << notification->mCallback.engine()->toScriptValue(action); - notification->mCallback.call(args); - - if (mDebugOutput) - qDebug() << "[JSONDB] notification received, Id:" << notify_uuid << "Action : " << action; - } -} - -void JsonDbComponent::notificationRemoved(int id) -{ - if (mDebugOutput) - qDebug() << "[JSONDB2] pending notification removed"; - - // ok, we have a pending notification - if (mPendingNotifications.contains(id)) - mKilledNotifications.insert(id); -} - -void JsonDbComponent::notificationRemoved(QString uuid) -{ - if (mDebugOutput) - qDebug() << "[JSONDB2] notification removed"; - - // remove a finished notification - QVariantMap arguments; - arguments.insert(JsonDbString::kUuidStr, uuid); - mJsonDb->remove(arguments); - - mNotifications.remove(uuid); -} - -int JsonDbComponent::addRequestInfo(int id, RequestType type, const QJSValue &object, const QJSValue &successCallback, const QJSValue &errorCallback) -{ - if (id < 0) { - qWarning() << "Missing database connection"; - return id; - } - if (!successCallback.isUndefined() && !successCallback.isCallable()) - qWarning() << "Success callback parameter "<<successCallback.toString()<<"is not a function."; - if (!errorCallback.isUndefined() && !errorCallback.isCallable()) - qWarning() << "Error callback parameter "<<errorCallback.toString()<<"is not a function."; - - JsonDbComponent::RequestInfo &info = mRequests[id]; - info.type = type; - info.object = object; - info.successCallback = successCallback; - info.errorCallback = errorCallback; - - return id; -} diff --git a/src/imports/jsondb-listmodel/jsondb-component.h b/src/imports/jsondb-listmodel/jsondb-component.h deleted file mode 100644 index fb023aa..0000000 --- a/src/imports/jsondb-listmodel/jsondb-component.h +++ /dev/null @@ -1,167 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JsonDbComponent_H -#define JsonDbComponent_H - -#include <QMap> -#include <QObject> -#include <QPointer> -#include <QJSValue> -#include <QSet> - -#include "jsondb-client.h" - -class JsonDbComponent; -class JsonDbNotificationHandle; - -QT_USE_NAMESPACE_JSONDB - -class JsonDbNotificationComponent: public QObject -{ - Q_OBJECT - - Q_PROPERTY(QString uuid READ uuid) -public: - ~JsonDbNotificationComponent(); - - QString uuid() const { return mUuid; } - Q_INVOKABLE void remove(); - -signals: - void notify(const QJSValue& object, const QString& action); - void removed(int id); - void removed(QString uuid); - -private: - JsonDbNotificationComponent(JsonDbComponent *repo); - - int mId; // the request id - QString mUuid; // for a fully created notification, this is the uuid of the db entry - QJSValue mCallback; - - friend class JsonDbComponent; - friend class JsonDbNotificationHandle; -}; - -class JsonDbNotificationHandle: public QObject -{ - Q_OBJECT - Q_PROPERTY(QString uuid READ uuid) -public: - JsonDbNotificationHandle(JsonDbNotificationComponent *notification); - ~JsonDbNotificationHandle(); - - QString uuid() const; - Q_INVOKABLE void remove(); -private: - QPointer<JsonDbNotificationComponent> mNotification; -}; - -class JsonDbComponent : public QObject -{ - Q_OBJECT - - Q_PROPERTY(bool debug READ hasDebugOutput WRITE setDebugOutput) - -public: - JsonDbComponent(QObject *parent = 0); - virtual ~JsonDbComponent(); - - bool hasDebugOutput() const { return mDebugOutput; } - void setDebugOutput(bool value) { mDebugOutput = value; } - - Q_INVOKABLE int create(const QJSValue &object, - const QJSValue &successCallback = QJSValue(QJSValue::UndefinedValue), - const QJSValue &errorCallback = QJSValue(QJSValue::UndefinedValue)); - Q_INVOKABLE int update(const QJSValue &object, - const QJSValue &successCallback = QJSValue(QJSValue::UndefinedValue), - const QJSValue &errorCallback = QJSValue(QJSValue::UndefinedValue)); - Q_INVOKABLE int remove(const QJSValue &object, - const QJSValue &successCallback = QJSValue(QJSValue::UndefinedValue), - const QJSValue &errorCallback = QJSValue(QJSValue::UndefinedValue)); - Q_INVOKABLE int find(const QJSValue &object, - const QJSValue &successCallback = QJSValue(QJSValue::UndefinedValue), - const QJSValue &errorCallback = QJSValue(QJSValue::UndefinedValue)); - - Q_INVOKABLE int query(const QJSValue &object, - const QJSValue &successCallback = QJSValue(QJSValue::UndefinedValue), - const QJSValue &errorCallback = QJSValue(QJSValue::UndefinedValue)); - - Q_INVOKABLE QJSValue notification(const QJSValue &object, - const QJSValue &actions, - const QJSValue &callback, - QJSValue errorCallback = QJSValue(QJSValue::UndefinedValue)); - - signals: - void response(QJSValue result, int id); - void error(const QString& message, int id); - - protected slots: - void jsonDbResponse(int, const QVariant &); - void jsonDbErrorResponse(int id, int code, const QString &message); - void jsonDbNotified(const QString& notify_uuid, const QVariant& object, const QString& action); - - void notificationRemoved(int id); - void notificationRemoved(QString uuid); - - private: - enum RequestType { Find, Create, Update, Remove, Notification }; - - int addRequestInfo(int id, RequestType type, const QJSValue &object, const QJSValue &successCallback, const QJSValue &errorCallback); - - bool mDebugOutput; - JsonDbClient *mJsonDb; // TODO: shouldn't this be a singleton? - - struct RequestInfo { - RequestType type; - QJSValue object; - QJSValue successCallback; - QJSValue errorCallback; - }; - - QMap<int, RequestInfo> mRequests; - QMap<int, JsonDbNotificationComponent*> mPendingNotifications; - QSet<int> mKilledNotifications; // notifications that were removed before they were really created - QMap<QString, JsonDbNotificationComponent*> mNotifications; -}; - -#endif diff --git a/src/imports/jsondb-listmodel/jsondb-listmodel.cpp b/src/imports/jsondb-listmodel/jsondb-listmodel.cpp deleted file mode 100644 index 1daa3e0..0000000 --- a/src/imports/jsondb-listmodel/jsondb-listmodel.cpp +++ /dev/null @@ -1,1263 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "jsondb-listmodel.h" -#include "jsondb-listmodel_p.h" -#include "private/jsondb-strings_p.h" - -#include <QJSEngine> -#include <QJSValueIterator> - - -#undef DEBUG_LIST_MODEL - -#ifdef DEBUG_LIST_MODEL -#define DEBUG() qDebug() << Q_FUNC_INFO -#else -#define DEBUG() if (0) qDebug() << QString("%1:%2").arg(__FUNCTION__).arg(__LINE__) -#endif - - -JsonDbListModelPrivate::JsonDbListModelPrivate(JsonDbListModel *q) - : q_ptr(q) - , chunkSize(40) - , lowWaterMark(10) - , maxCacheSize(0) // unlimited cache - , totalRowCount(0) - , cacheStart(0) - , cacheEnd(0) - , newChunkOffset(0) - , totalCountRequestId(-1) - , lastFetchedIndex(-1) - , requestInProgress(false) - , componentComplete(false) - , resetModel(true) - , updateRecieved(false) - , totalRowCountRecieved(false) - , state(None) - , jsonDbConnection(JsonDbConnection::instance()) -{ -} - -void JsonDbListModelPrivate::init() -{ - Q_Q(JsonDbListModel); - q->connect(&jsonDb, SIGNAL(response(int,QVariant)), - q, SLOT(_q_jsonDbResponse(int,QVariant)), - Qt::QueuedConnection); - q->connect(&jsonDb, SIGNAL(error(int,int,QString)), - q, SLOT(_q_jsonDbErrorResponse(int,int,QString)), - Qt::QueuedConnection); - q->connect(&jsonDb, SIGNAL(notified(QString,QVariant,QString)), - q, SLOT(_q_jsonDbNotified(QString,QVariant,QString)), - Qt::QueuedConnection); - q->connect(q, SIGNAL(needAnotherChunk(int)), q, SLOT(_q_requestAnotherChunk(int)), Qt::QueuedConnection); -} - -JsonDbListModelPrivate::~JsonDbListModelPrivate() -{ - // Why do we need to do this while destroying the object - if (!notifyUuid.isEmpty()) { - QVariantMap notificationObject; - notificationObject.insert("_uuid", notifyUuid); - jsonDb.remove(notificationObject); - } -} - -void JsonDbListModelPrivate::clearCache(int newStart) -{ - cacheStart = newStart; - cacheEnd = newStart; - objectUuids.clear(); - objectSortValues.clear(); - data.clear(); - cachedUuids.clear(); - lastFetchedItem.clear(); - lastFetchedIndex = -1; -} - -int JsonDbListModelPrivate::makeSpaceFor(int count, int insertAt) -{ - int itemsToRemove = itemsInCache() + count - maxCacheSize; - // Check for unlimited cache - if (maxCacheSize <= 0) - itemsToRemove = 0; - int index = 0; - int newCacheStart = insertAt; - int newCacheEnd = newCacheStart + count; - if (newCacheStart == cacheEnd) { - // adding elements in the end. - } else if (newCacheEnd == cacheStart) { - // adding elements in the beginning. - index = itemsInCache() - itemsToRemove; - } else if (newCacheStart >= cacheStart && newCacheEnd <= cacheEnd) { - // adding elements within the cached elements - // don't remove any, we should ignore duplicates. - return 0; - } else if (newCacheStart <= cacheStart && newCacheEnd >= cacheEnd) { - // new cache will include the current one, so skip it - return 0; - } else if (newCacheEnd < cacheStart || newCacheStart > cacheEnd) { - // we need to invalidate the cache, we only store elements in sequence. - itemsToRemove = itemsInCache(); - clearCache(insertAt); - return itemsToRemove; - } else if (newCacheEnd < cacheEnd) { - // adding items in the beginning, with overlap. - itemsToRemove -= (newCacheEnd - cacheStart); - index = itemsInCache() - itemsToRemove; - } else if (newCacheStart > cacheStart) { - // adding items towards the end, with overlap - itemsToRemove -= (cacheEnd - newCacheStart); - } - if (itemsToRemove <= 0) - return 0; - for (int i = 0; i < itemsToRemove; i++) { - const QString &uuid = cachedUuids.at(i+index); - Q_ASSERT(objectSortValues.contains(uuid)); - const JsonDbSortKey &key = objectSortValues.value(uuid); - Q_ASSERT(objectUuids.contains(key, uuid)); - objectUuids.remove(key, uuid); - objectSortValues.remove(uuid); - data.remove(uuid); - } - QList<QString>::iterator first = cachedUuids.begin()+index; - QList<QString>::iterator last = first+itemsToRemove; - cachedUuids.erase(first, last); - - if (index > 0) - cacheEnd -= itemsToRemove; - else - cacheStart += itemsToRemove; - return itemsToRemove; -} - -JsonDbSortKey JsonDbListModelPrivate::sortKey(const QVariantMap &object) -{ - return JsonDbSortKey(object, orderDirections, orderPaths); -} - -// removes an item from the cache -void JsonDbListModelPrivate::removeItem(int index) -{ - if (cachedUuids.size() <= index) { - qWarning() << "removeItem index not in cache"; - return; - } - - const QString &uuid = cachedUuids[index]; - const JsonDbSortKey &key = objectSortValues.value(uuid); - objectUuids.remove(key, uuid); - objectSortValues.remove(uuid); - data.remove(uuid); - cachedUuids.removeAt(index); - cacheEnd = qMax(cacheStart, cacheEnd-1); -} - -// finds the object position within the cache limits -int JsonDbListModelPrivate::findSortedPosition(const QString& uuid) -{ - int pos = 0; - QMap<JsonDbSortKey,QString>::const_iterator it; - QMap<JsonDbSortKey,QString>::const_iterator end = objectUuids.end(); - for (it = objectUuids.begin(); it != end; it++, pos++) { - if (it.value() == uuid) - return pos; - } - // uuid not found in objectUuids - return -1; -} - -// insert item notification handler -void JsonDbListModelPrivate::insertItem(const QVariantMap &item, bool emitSignals) -{ - Q_Q(JsonDbListModel); - Q_UNUSED(item); - - lastFetchedItem.clear(); - lastFetchedIndex = -1; - clearCache(cacheStart); - totalRowCount++; - if (emitSignals) { - // When a new item is added, the position of the item is not known - // to the model. We will clear the cache and notify that an item - // is added at the end + all data is changed. - QModelIndex parent; - q->beginInsertRows(parent, totalRowCount-1, totalRowCount-1); - q->endInsertRows(); - emit q->countChanged(); - emit q->rowCountChanged(); - QModelIndex start = q->createIndex(0,0); - QModelIndex end = q->createIndex(totalRowCount-1, 0); - emit q->dataChanged(start, end); - } -} - -// deleteitem notification handler -void JsonDbListModelPrivate::deleteItem(const QVariantMap &item, bool emitSignals) -{ - Q_Q(JsonDbListModel); - - lastFetchedItem.clear(); - lastFetchedIndex = -1; - const QString &uuid = item.value("_uuid", QString()).toString(); - int index = cachedUuids.indexOf(uuid); - if (index != -1) { - // When item is in the cache emit signals using the exact position. - QModelIndex parent; - if (emitSignals) - q->beginRemoveRows(parent, cacheStart+index, cacheStart+index); - removeItem(index); - totalRowCount = qMax(0, totalRowCount -1); - if (emitSignals) { - q->endRemoveRows(); - emit q->countChanged(); - emit q->rowCountChanged(); - } - } else { - // Model dosen't know the position from where the item is deleted. - // We will clear the cache and notify that an item is removed - // from the end + all data is changed. - QModelIndex parent; - if (!totalRowCount) - emitSignals = false; - if (emitSignals) - q->beginRemoveRows(parent, totalRowCount-1, totalRowCount-1); - clearCache(cacheStart); - totalRowCount = qMax(0, totalRowCount -1); - if (emitSignals) { - q->endRemoveRows(); - emit q->countChanged(); - emit q->rowCountChanged(); - QModelIndex start = q->createIndex(0,0); - QModelIndex end = q->createIndex((totalRowCount ? totalRowCount-1 :0), 0); - emit q->dataChanged(start, end); - } - } -} - -// updateitem notification handler -void JsonDbListModelPrivate::updateItem(const QVariantMap &item) -{ - Q_Q(JsonDbListModel); - lastFetchedItem.clear(); - lastFetchedIndex = -1; - const QString &uuid = item.value("_uuid").toString(); - // if item is currently in cache. - if (objectSortValues.contains(uuid)) { - int currentIndex = findSortedPosition(uuid); - deleteItem(item, false); - insertItem(item, false); - int newIndex = findSortedPosition(uuid); - if (currentIndex == newIndex) { - // emit signal for the changed item. - QModelIndex modelIndex = q->createIndex(newIndex, 0); - emit q->dataChanged(modelIndex, modelIndex); - return; - } - } - // We are not sure about the position of the updated item, - // clear the cache and notify that all data is changed. - clearCache(cacheStart); - QModelIndex start = q->createIndex(0,0); - QModelIndex end = q->createIndex((totalRowCount ? totalRowCount-1 :0), 0); - emit q->dataChanged(start, end); -} - -void JsonDbListModelPrivate::_q_requestAnotherChunk(int offset) -{ - if (requestInProgress || query.isEmpty()) - return; - int maxItemsToFetch = chunkSize; - if (offset < 0) { - maxItemsToFetch += offset; - offset = 0; - } - newChunkOffset = offset; - if (newChunkOffset >= cacheStart && newChunkOffset < cacheEnd) - newChunkOffset = cacheEnd; - // now fetch more - QVariantMap request; - request.insert(JsonDbString::kQueryStr, query); - request.insert("offset", newChunkOffset); - request.insert("limit", maxItemsToFetch); - resetModel = false; - requestIds.insert(jsonDb.find(request)); - requestInProgress = true; -} - -void JsonDbListModelPrivate::fetchChunkSynchronous(int offset) -{ - // Ignore previous reqests - if (requestInProgress) { - requestIds.clear(); - } - Q_ASSERT(!query.isEmpty()); - int maxItemsToFetch = chunkSize; - if (offset < 0) { - maxItemsToFetch += offset; - offset = 0; - } - newChunkOffset = offset; - if (newChunkOffset >= cacheStart && newChunkOffset < cacheEnd) - newChunkOffset = cacheEnd; - // now fetch more - QVariantMap request; - request.insert(JsonDbString::kQueryStr, query); - request.insert("offset", newChunkOffset); - request.insert("limit", maxItemsToFetch); - resetModel = false; - requestInProgress = true; - QVariantMap v = jsonDbConnection->sync(JsonDbConnection::makeQueryRequest(query, newChunkOffset, maxItemsToFetch)).toMap(); - requestInProgress = false; - updateCache(v); -} - -void JsonDbListModelPrivate::populateModel() -{ - Q_Q(JsonDbListModel); - clearCache(); - updateRecieved = false; - totalRowCountRecieved = false; - totalRowCount = 0; - // Request the total count - QVariantMap requestCount; - QString countQuery = query+"[count]"; - requestCount.insert(JsonDbString::kQueryStr, countQuery); - - totalCountRequestId = jsonDb.find(requestCount); - - QVariantMap requestQuery; - //Request at least 2 chunks of data - requestQuery.insert(JsonDbString::kQueryStr, query); - requestQuery.insert("offset", newChunkOffset); - int itemsToGet = chunkSize*2; - if (maxCacheSize) - itemsToGet = qMin(itemsToGet, maxCacheSize); - requestQuery.insert("limit",itemsToGet); - resetModel = true; - requestIds.insert(jsonDb.find(requestQuery)); - requestInProgress = true; - state = JsonDbListModelPrivate::Querying; - emit q->stateChanged(); -} - -QVariantMap JsonDbListModelPrivate::getItem(int index, bool handleCacheMiss, bool &cacheMiss) -{ - QVariantMap item; - if (index < 0 || index >= totalRowCount) - return item; - if (index < cacheStart || index >= cacheEnd) { - DEBUG()<<"Index "<< index<<"Out of Range, fetch more...."<<cacheStart<<cacheEnd; - // clear and fetch new set of items - if (handleCacheMiss) { - // clearing the cache is done by makeSpaceFor() - fetchChunkSynchronous(qMax(index-(chunkSize/2), 0)); - } else { - cacheMiss = true; - return item; - } - } - - if (cachedUuids.size() <= (index - cacheStart)) { - qWarning() << "Could not get Item"; - return item; - } - QString uuid = cachedUuids[index - cacheStart]; - item = data.value(uuid); - if ((lowWaterMark > 0) && (data.size() < totalRowCount)) { - if ((cacheEnd - index) < lowWaterMark) { - _q_requestAnotherChunk(cacheEnd); - } else if (cacheStart && (index - cacheStart) < lowWaterMark) { - _q_requestAnotherChunk(qMax(cacheStart-chunkSize, 0)); - } - } - cacheMiss = false; - lastFetchedItem = item; - lastFetchedIndex = index; - return item; -} - -QVariantMap JsonDbListModelPrivate::getItem(const QModelIndex &modelIndex, int role, - bool handleCacheMiss, bool &cacheMiss) -{ - Q_UNUSED(role); - return getItem(modelIndex.row(), handleCacheMiss, cacheMiss); -} - -static QVariant lookupProperty(QVariantMap object, const QStringList &path) -{ - if (!path.size()) { - return QVariant(); - } - QVariantMap emptyMap; - QVariantList emptyList; - QVariantList objectList; - for (int i = 0; i < path.size() - 1; i++) { - const QString &key = path.at(i); - // this part of the property is a list - if (!objectList.isEmpty()) { - bool ok = false; - int index = key.toInt(&ok); - if (ok && (index >= 0) && (objectList.count() > index)) { - if (objectList.at(index).type() == QVariant::List) { - objectList = objectList.at(index).toList(); - object = emptyMap; - } else { - object = objectList.at(index).toMap(); - objectList = emptyList; - } - continue; - } - } - // this part is a map - if (object.contains(key)) { - if (object.value(key).type() == QVariant::List) { - objectList = object.value(key).toList(); - object = emptyMap; - } else { - object = object.value(key).toMap(); - objectList = emptyList; - } - } else { - return QVariant(); - } - } - const QString &key = path.last(); - // get the last part from the list - if (!objectList.isEmpty()) { - bool ok = false; - int index = key.toInt(&ok); - if (ok && (index >= 0) && (objectList.count() > index)) { - return objectList.at(index); - } - } - // if the last part is in a map - return object.value(key); -} - -static QVariantMap updateProperty(QVariantMap item, const QStringList &propertyChain, QVariant value) -{ - if (propertyChain.size() < 1) { - qCritical() << "updateProperty" << "empty property chain" << item; - } else if (propertyChain.size() == 1) { - item.insert(propertyChain[0], value.toString()); - } else { - QString property = propertyChain[0]; - QVariant newChild = updateProperty(item.value(property).toMap(), propertyChain.mid(1), value); - item.insert(property, newChild); - } - return item; -} - -/*! - \qmlmodule QtAddOn.JsonDb 1.0 - - QML interface to Json Database. -*/ - -/*! - \qmltype JsonDbListModel - \instantiates JsonDbListModel - \ingroup qml-working-with-data - \inqmlmodule QtAddOn.JsonDb 1.0 - \inherits ListModel - \since 1.0 - \brief Provides a ListModel displaying data items matching a query. - - The JsonDbListModel provides a ListModel usable with views such as - ListView or GridView displaying data items matching a query. - - \code - JsonDbListModel { - id: contactsModel - query: "[?_type=\"Contact\"]" - roleNames: ["firstName", "lastName", "phoneNumber"] - } - ListView { - model: contactsModel - Row { - spacing: 10 - Text { - text: firstName + " " + lastName - } - Text { - text: phoneNumber - } - } - } - \endcode -*/ - -/*! - \qmlproperty int QtAddOn.JsonDb::JsonDbListModel::rowCount - - Returns the number of rows in the model. -*/ - -/*! - \qmlproperty string QtAddOn.JsonDb::JsonDbListModel::query - - Returns the model's query. -*/ - -JsonDbListModel::JsonDbListModel(QObject *parent) - : QAbstractListModel(parent), d_ptr(new JsonDbListModelPrivate(this)) -{ - Q_D(JsonDbListModel); - d->init(); -} - -JsonDbListModel::~JsonDbListModel() -{ -} - -void JsonDbListModel::classBegin() -{ -} - -void JsonDbListModel::componentComplete() -{ - Q_D(JsonDbListModel); - d->componentComplete = true; - if (!d->query.isEmpty()) { - d->populateModel(); - } -} - -void JsonDbListModelPrivate::createOrUpdateNotification() -{ - if (!notifyUuid.isEmpty()) { - QVariantMap notificationObject; - notificationObject.insert("_uuid", notifyUuid); - jsonDb.remove(notificationObject); - notifyUuid.clear(); - } - - const JsonDbClient::NotifyTypes actions = JsonDbClient::NotifyCreate | JsonDbClient::NotifyUpdate | JsonDbClient::NotifyRemove; - notificationObjectRequestIds.insert(jsonDb.notify(actions, query)); - DEBUG() << notificationObjectRequestIds; -} - -/*! - \qmlmethod QtAddOn.JsonDb::JsonDbListModel::sectionIndex(section, successCallback, errorCallback) - */ -int JsonDbListModel::sectionIndex(const QString §ion, - const QJSValue &successCallback, - const QJSValue &errorCallback) -{ - Q_D(JsonDbListModel); - // Find the count of items "< section" - QString sectionCountQueryLT = d->queryWithoutSort+"[?"+d->orderProperties[0]+"<\""+section+"\"][count]"; - QVariantMap request; - request.insert(JsonDbString::kQueryStr, sectionCountQueryLT); - int id = d->jsonDb.find(request); - // Register any valid callbacks - CallbackInfo info; - if (successCallback.isCallable() - || errorCallback.isCallable()) { - info.successCallback = successCallback; - info.errorCallback = errorCallback; - d->sectionIndexRequestIds.insert(id, info); - } - return id; -} - -/*! - \qmlproperty int QtAddOn.JsonDb::JsonDbListModel::count - - Returns the number of items in the model. -*/ -int JsonDbListModel::count() const -{ - Q_D(const JsonDbListModel); - return d->totalRowCount; -} - -QModelIndex JsonDbListModel::index(int row, int , const QModelIndex &) const -{ - return createIndex(row, 0); -} - -int JsonDbListModel::rowCount(const QModelIndex &) const -{ - Q_D(const JsonDbListModel); - return d->totalRowCount; -} - -QVariant JsonDbListModel::data(const QModelIndex &modelIndex, int role) const -{ - Q_D(const JsonDbListModel); - QVariantMap item; - if (!(d->lastFetchedIndex == modelIndex.row()) || (d->lastFetchedIndex == -1)) { - JsonDbListModel * pThis = const_cast<JsonDbListModel *>(this); - bool cacheMiss = false; - item = pThis->d_func()->getItem(modelIndex, role, true, cacheMiss); - } else { - item = d->lastFetchedItem; - } - - QVariant result; - QStringList property = d->properties[role]; - result = lookupProperty(item, property); - - return result; -} - -QHash<int, QByteArray> JsonDbListModel::roleNames() const -{ - Q_D(const JsonDbListModel); - return d->roleNames; -} - -void JsonDbListModel::set(int index, const QJSValue& valuemap, - const QJSValue &successCallback, - const QJSValue &errorCallback) -{ - Q_D(JsonDbListModel); - d->set(index, valuemap, successCallback, errorCallback); -} - -void JsonDbListModelPrivate::set(int index, const QJSValue& valuemap, - const QJSValue &successCallback, - const QJSValue &errorCallback) -{ - Q_Q(JsonDbListModel); - if (!valuemap.isObject() || valuemap.isArray()) { - qDebug() << q->tr("set: value is not an object"); - return; - } - // supports only changing an exixting item. - if (index >= totalRowCount || index < 0) { - qDebug() << q->tr("set: index %1 out of range").arg(index); - return; - } - - bool cacheMiss = false; - QVariantMap item = getItem(index, false, cacheMiss); - if (cacheMiss) { - fetchChunkSynchronous(qMax(index-(chunkSize/2), 0)); - //TODO, do some error checking. - item = getItem(index, false, cacheMiss); - if (cacheMiss) - DEBUG() << "Could not fetch item at index : %1" << index; - } - - QJSValueIterator it(valuemap); - while (it.hasNext()) { - it.next(); - QString name = it.name(); - QVariant v = it.value().toVariant(); - int role = q->roleFromString(name); - if (role == -1) { - qDebug() << q->tr("set: property %1 invalid").arg(name); - continue; - } - item = updateProperty(item, properties[role], v); - } - - lastFetchedItem.clear(); - lastFetchedIndex = -1; - // Item will be updated through the update notification - CallbackInfo info; - info.index = index; - int id = jsonDb.update(item); // possibly change to variantToQson(item).. - // Register any valid callbacks - if (successCallback.isCallable() - || errorCallback.isCallable()) { - info.successCallback = successCallback; - info.errorCallback = errorCallback; - updateRequestIds.insert(id, info); - } -} - -void JsonDbListModel::setProperty(int index, const QString& property, const QVariant& value, - const QJSValue &successCallback, - const QJSValue &errorCallback) -{ - Q_D(JsonDbListModel); - d->setProperty(index, property, value, successCallback, errorCallback); -} - -void JsonDbListModelPrivate::setProperty(int index, const QString& property, const QVariant& value, - const QJSValue &successCallback, - const QJSValue &errorCallback) -{ - Q_Q(JsonDbListModel); - // supports only changing an exixting item. - if (index >= totalRowCount || index < 0) { - qDebug() << q->tr("set: index %1 out of range").arg(index); - return; - } - - bool cacheMiss = false; - QVariantMap item = getItem(index, false, cacheMiss); - if (cacheMiss) { - fetchChunkSynchronous(qMax(index-(chunkSize/2), 0)); - //TODO, do some error checking. - item = getItem(index, false, cacheMiss); - if (cacheMiss) - DEBUG() << "Could not fetch item with index : " << index; - } - - int role = q->roleFromString(property); - if (role == -1) { - qDebug() << q->tr("set: property %1 invalid").arg(property); - return; - } - item = updateProperty(item, properties[role], value); - - lastFetchedItem.clear(); - lastFetchedIndex = -1; - - int id = jsonDb.update(item); // possibly change to variantToQson(item).. - // Register any valid callbacks - if (successCallback.isCallable() - || errorCallback.isCallable()) { - - // Item will be updated through the update notification - CallbackInfo info; - info.index = index; - info.successCallback = successCallback; - info.errorCallback = errorCallback; - updateRequestIds.insert(id, info); - } -} - -void JsonDbListModel::fetchMore(const QModelIndex &) -{ - DEBUG() << endl; -} - -bool JsonDbListModel::canFetchMore(const QModelIndex &) const -{ - DEBUG() << endl; - return false; -} - -void JsonDbListModel::setQuery(const QString &newQuery) -{ - Q_D(JsonDbListModel); - - const QString oldQuery = d->query; - d->query = newQuery; - d->state = JsonDbListModelPrivate::Querying; - emit stateChanged(); - if (oldQuery != newQuery) { - d->findSortOrder(); - } - - if (!d->componentComplete) - return; - - d->populateModel(); -} - -/*! - \qmlproperty string QtAddOn.JsonDb::JsonDbListModel::query - - Returns the query used by the model to fetch items from the database. - - In the following example, the \a JsonDbListModel would contain all the objects with \a _type contains the value \a "CONTACT" - - \qml - JsonDbListModel { - id: listModel - query: "[?_type=\"CONTACT\"]" - } - \endqml - -*/ -QString JsonDbListModel::query() const -{ - Q_D(const JsonDbListModel); - return d->query; -} - -void JsonDbListModel::setLimit(int newLimit) -{ - Q_D(JsonDbListModel); - d->maxCacheSize = newLimit; -} - -/*! - \qmlproperty int QtAddOn.JsonDb::JsonDbListModel::limit - - The number of items to be cached. -*/ -int JsonDbListModel::limit() const -{ - Q_D(const JsonDbListModel); - return d->maxCacheSize; -} - -void JsonDbListModel::setChunkSize(int newChunkSize) -{ - Q_D(JsonDbListModel); - d->chunkSize = newChunkSize; -} - -/*! - \qmlproperty int QtAddOn.JsonDb::JsonDbListModel::chunkSize - - The number of items to fetch at a time from the database. - - The model uses a heuristic to fetch only as many items as needed by - the view. Each time it requests items it fetches \a chunkSize items. -*/ -int JsonDbListModel::chunkSize() const -{ - Q_D(const JsonDbListModel); - return d->chunkSize; -} - -void JsonDbListModel::setLowWaterMark(int newLowWaterMark) -{ - Q_D(JsonDbListModel); - d->lowWaterMark = newLowWaterMark; -} - -/*! - \qmlproperty int QtAddOn.JsonDb::JsonDbListModel::lowWaterMark - - Controls when to fetch more items from the database. - - JsonDbListModel fetch \a chunkSize more items when the associated - view requests an item within \a lowWaterMark from the end of the - items previously fetched. -*/ -int JsonDbListModel::lowWaterMark() const -{ - Q_D(const JsonDbListModel); - return d->lowWaterMark; -} - - -/*! - \qmlproperty ListOrObject QtAddOn.JsonDb::JsonDbListModel::roleNames - - Controls which properties to expose from the objects matching the query. - - Setting \a roleNames to a list of strings causes the model to fetch - those properties of the objects and expose them as roles to the - delegate for each item viewed. - - \code - JsonDbListModel { - query: "[?_type=\"MyType\"]" - roleNames: ['a', 'b'] - } - ListView { - model: listModel - Text { - text: a + ":" + b - } - \endcode - - Setting \a roleNames to a dictionary remaps properties in the object - to the specified roles in the model. - - In the following example, role \a a would yield the value of - property \a aLongName in the objects. Role \a liftedProperty would - yield the value of \a o.nested.property for each matching object \a - o in the database. - - \code - function makeRoleNames() { - return { 'a': 'aLongName', 'liftedProperty': 'nested.property' }; - } - JsonDbListModel { - id: listModel - query: "[?_type=\"MyType\"]" - roleNames: makeRoleNames() - } - ListView { - model: listModel - Text { - text: a + " " + liftedProperty - } - } - \endcode -*/ -QVariant JsonDbListModel::scriptableRoleNames() const -{ - Q_D(const JsonDbListModel); - - DEBUG() << d->roleMap; - return d->roleMap; -} - -QString removeArrayOperator(QString propertyName) -{ - propertyName.replace(QLatin1Char('['), QLatin1Char('.')); - propertyName.remove(QLatin1Char(']')); - return propertyName; -} - -void JsonDbListModel::setScriptableRoleNames(const QVariant &vroles) -{ - Q_D(JsonDbListModel); - d->properties.clear(); - d->roleNames.clear(); - if (vroles.type() == QVariant::Map) { - QVariantMap roles = vroles.toMap(); - d->roleMap = roles; - int i = 0; - for (QVariantMap::const_iterator it = roles.begin(); it != roles.end(); ++it) { - d->roleNames.insert(i, it.key().toLatin1()); - d->properties.insert(i, removeArrayOperator(it.value().toString()).split('.')); - i++; - } - } else { - QVariantList roleList = vroles.toList(); - d->roleMap.clear(); - for (int i = 0; i < roleList.size(); i++) { - QString role = roleList[i].toString(); - d->roleMap[role] = role; - d->roleNames.insert(i, role.toLatin1()); - d->properties.insert(i, removeArrayOperator(role).split('.')); - } - } - DEBUG() << d->roleNames; -} - -QString JsonDbListModel::state() const -{ - Q_D(const JsonDbListModel); - switch (d->state) { - case JsonDbListModelPrivate::None: - return QString("None"); - case JsonDbListModelPrivate::Querying: - return QString("Querying"); - case JsonDbListModelPrivate::Ready: - return QString("Ready"); - default: - return QString("Error"); - } -} - -QString JsonDbListModel::toString(int role) const -{ - Q_D(const JsonDbListModel); - if (d->roleNames.contains(role)) - return QString::fromLatin1(d->roleNames.value(role)); - else - return QString(); -} - -int JsonDbListModel::roleFromString(const QString &roleName) const -{ - Q_D(const JsonDbListModel); - return d->roleNames.key(roleName.toLatin1(), -1); -} - -void JsonDbListModelPrivate::updateCache(const QVariantMap &v) -{ - Q_Q(JsonDbListModel); - QVariantMap m = v; - if (m.contains("data")) { - QVariantList items = m.value("data").toList(); - int size = items.size(); - int sizeAdded = 0; - if (size) { - DEBUG()<<"OLD Cache Start"<<cacheStart<<"Cache End:"<<cacheEnd; - if (resetModel) - q->beginResetModel(); - makeSpaceFor(size, newChunkOffset); - bool appendToCache = (newChunkOffset >= cacheEnd) ? true : false; - int insertAt = appendToCache ? itemsInCache() : 0; - DEBUG()<<"INSERT AT :"<<insertAt<<"Elements Retrieved:"<<size<<"ChunkOffset:"<<newChunkOffset<<appendToCache << itemsInCache(); - DEBUG()<<"Cache Start"<<cacheStart<<"Cache End:"<<cacheEnd<<"Total Rows = "<<totalRowCount; - // Add the new result to cache. - for (int i = 0; i < size; i++) { - QVariantMap item = items.value(i).toMap(); - const QString &uuid = item.value(JsonDbString::kUuidStr).toString(); - if (objectSortValues.contains(uuid)){ - break; - } - JsonDbSortKey key = sortKey(item); - objectUuids.insert(key, uuid); - objectSortValues.insert(uuid, key); - data[uuid] = item; - cachedUuids.insert(insertAt++, uuid); - sizeAdded++; - } - DEBUG()<<"sizeAdded:"<<sizeAdded; - // Update the cache limits - if (!itemsInCache()) { - cacheStart = newChunkOffset; - cacheEnd = cacheStart + sizeAdded; - } else if (appendToCache) { - cacheEnd += sizeAdded; - } else { - cacheStart = qMax(0, cacheStart-sizeAdded); - } - Q_ASSERT(cachedUuids.count() == data.count()); - } - if (resetModel && totalRowCountRecieved) - resetModelFinished(); - else - updateRecieved = true; - } -} - -void JsonDbListModelPrivate::_q_jsonDbResponse(int id, const QVariant &v) -{ - QVariantMap m = v.toMap(); - if (requestIds.contains(id)) { - requestIds.remove(id); - requestInProgress = false; - updateCache(m); - } else if (totalCountRequestId == id) { - QVariantList items = m.value("data").toList(); - m = items.value(0).toMap(); - totalRowCount = m.value("count").toInt(); - totalRowCountRecieved = true; - if (updateRecieved) - resetModelFinished(); - } else if (notificationObjectRequestIds.contains(id)) { - notificationObjectRequestIds.remove(id); - notifyUuid = m.value(JsonDbString::kUuidStr).toString(); - } else if (updateRequestIds.constFind(id) != updateRequestIds.constEnd()) { - CallbackInfo info = updateRequestIds.value(id); - if (info.successCallback.isCallable()) { - QJSValueList args; - QJSValue scriptResult = info.successCallback.engine()->toScriptValue(id); - args << scriptResult; - scriptResult = info.successCallback.engine()->toScriptValue(info.index); - args << scriptResult; - info.successCallback.call(args); - } - updateRequestIds.remove(id); - } else if (sectionIndexRequestIds.constFind(id) != sectionIndexRequestIds.constEnd()) { - CallbackInfo info = sectionIndexRequestIds.value(id); - if (info.successCallback.isCallable()) { - QVariantList items = m.value("data").toList(); - m = items.value(0).toMap(); - QJSValueList args; - QJSValue scriptResult = info.successCallback.engine()->toScriptValue(id); - args << scriptResult; - scriptResult = info.successCallback.engine()->toScriptValue(m.value("count").toInt()); - args << scriptResult; - info.successCallback.call(args); - } - sectionIndexRequestIds.remove(id); - } -} - -void JsonDbListModelPrivate::resetModelFinished() -{ - Q_Q(JsonDbListModel); - q->endResetModel(); - emit q->countChanged(); - emit q->rowCountChanged(); - state = Ready; - emit q->stateChanged(); - resetModel = false; - pendingNotifications.clear(); - createOrUpdateNotification(); -} - -bool operator<(const QVariant& a, const QVariant& b) -{ - if ((a.type() == QVariant::Int) && (b.type() == QVariant::Int)) - return a.toInt() < b.toInt(); - else if ((a.type() == QVariant::Double) && (b.type() == QVariant::Double)) - return a.toFloat() < b.toFloat(); - return (QString::compare( a.toString(), b.toString(), Qt::CaseInsensitive ) < 0); -} - -bool operator>(const QVariant& a, const QVariant& b) { return b < a; } - -bool JsonDbListModelPrivate::findSortOrder() -{ - QRegExp orderMatch("\\[([/\\\\[\\]])[ ]*([^\\[\\]]+)[ ]*\\]"); - orderDirections.clear(); - orderProperties.clear(); - orderPaths.clear(); - int matchIndex = 0, firstMatch = -1; - DEBUG() << query; - while ((matchIndex = orderMatch.indexIn(query, matchIndex)) >= 0) { - orderDirections << orderMatch.cap(1); - orderProperties << orderMatch.cap(2); - orderPaths << orderMatch.cap(2).split('.'); - DEBUG() << matchIndex; - if (firstMatch == -1) - firstMatch = matchIndex; - matchIndex += orderMatch.matchedLength(); - } - queryWithoutSort = query.mid(0,firstMatch); - if (orderPaths.isEmpty()) { - orderDirections << "/"; - orderProperties << "_uuid"; - orderPaths << orderProperties[0].split('.'); - } - DEBUG() << orderDirections << orderProperties << orderPaths; - return true; -} - -void JsonDbListModelPrivate::_q_jsonDbNotified(const QString& currentNotifyUuid, const QVariant &v, const QString &action) -{ - QVariantMap item = v.toMap(); - if (currentNotifyUuid != notifyUuid) { - return; - } - if (resetModel) { - // we have not received the first chunk, wait for it before processing notifications - NotifyItem pending; - pending.notifyUuid = currentNotifyUuid; - pending.item = item; - pending.action = action; - pendingNotifications.append(pending); - return; - } - if (action == JsonDbString::kCreateStr) { - insertItem(item); - return ; - } else if (action == JsonDbString::kRemoveStr) { - deleteItem(item); - return ; - } else if (action == JsonDbString::kUpdateStr) { - updateItem(item); - return ; - } - -} - -void JsonDbListModelPrivate::_q_jsonDbErrorResponse(int id, int code, const QString &message) -{ - if (requestIds.contains(id)) { - requestIds.remove(id); - qWarning() << QString("JsonDb error: %1 %2").arg(code).arg(message); - } else if (updateRequestIds.constFind(id) != updateRequestIds.constEnd()) { - CallbackInfo info = updateRequestIds.value(id); - if (info.errorCallback.isCallable()) { - QJSValueList args; - args << info.errorCallback.engine()->toScriptValue(id); - args << info.errorCallback.engine()->toScriptValue(info.index); - args << info.errorCallback.engine()->toScriptValue(code); - args << info.errorCallback.engine()->toScriptValue(message); - info.errorCallback.call(args); - } - updateRequestIds.remove(id); - } -} - -void JsonDbListModelPrivate::_q_jsonDbErrorResponse(int code, const QString &message) -{ - qWarning() << QString("JsonDb error: %1 %2").arg(code).arg(message); -} - -/*! - \qmlmethod QVariant JsonDbListModel::get(int idx, const QString &property) const - \since 1.0 -*/ -QVariant JsonDbListModel::get(int idx, const QString &property) const -{ - int role = roleFromString(property); - if (role >= 0) - return data(index(idx, 0), role); - else - return QVariant(); -} - - -class JsonDbSortKeyPrivate : public QSharedData { -public: - JsonDbSortKeyPrivate(QStringList directions, QVariantList keys) : mDirections(directions), mKeys(keys) {} - const QStringList &directions() const { return mDirections; } - const QVariantList &keys() const { return mKeys; } -private: - QStringList mDirections; - QVariantList mKeys; - JsonDbSortKeyPrivate(const JsonDbSortKeyPrivate&); -}; - -JsonDbSortKey::JsonDbSortKey() -{ -} - -JsonDbSortKey::JsonDbSortKey(const QVariantMap &object, const QStringList &directions, const QList<QStringList> &paths) -{ - QVariantList keys; - for (int i = 0; i < paths.size(); i++) - keys.append(lookupProperty(object, paths[i])); - d = new JsonDbSortKeyPrivate(directions, keys); -} - -JsonDbSortKey::JsonDbSortKey(const JsonDbSortKey&other) - : d(other.d) -{ -} - -const QVariantList &JsonDbSortKey::keys() const { return d->keys(); } -const QStringList &JsonDbSortKey::directions() const { return d->directions(); } - -QString JsonDbSortKey::toString() const -{ - QStringList result; - for (int i = 0; i < d->keys().size(); i++) { - result.append(QString("%1%2") - .arg(d->directions()[i]) - .arg(d->keys()[i].toString())); - } - return result.join(", "); -} - -bool operator <(const JsonDbSortKey &a, const JsonDbSortKey &b) -{ - const QVariantList &akeys = a.keys(); - const QVariantList &bkeys = b.keys(); - const QStringList &adirs = a.directions(); - for (int i = 0; i < akeys.size(); i++) { - const QVariant &akey = akeys[i]; - const QVariant &bkey = bkeys[i]; - if (akey != bkey) { - if (adirs[i] == "/") - return akey < bkey; - else - return akey > bkey; - } - } - return false; -} - -#include "moc_jsondb-listmodel.cpp" diff --git a/src/imports/jsondb-listmodel/jsondb-listmodel.h b/src/imports/jsondb-listmodel/jsondb-listmodel.h deleted file mode 100644 index 599f256..0000000 --- a/src/imports/jsondb-listmodel/jsondb-listmodel.h +++ /dev/null @@ -1,153 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JsonDbListModel_H -#define JsonDbListModel_H - -#include <QAbstractListModel> -#include <QHash> -#include <QMultiMap> -#include <QSet> -#include <QSharedDataPointer> -#include <QStringList> -#include <QQmlParserStatus> -#include <QJSValue> -#include <QScopedPointer> - -#include "jsondb-global.h" - -QT_USE_NAMESPACE_JSONDB - -class JsonDbSortKeyPrivate; - -class JsonDbSortKey { -public: - JsonDbSortKey(); - JsonDbSortKey(const QVariantMap &object, const QStringList &directions, const QList<QStringList> &paths); - JsonDbSortKey(const JsonDbSortKey&); - - const QVariantList &keys() const; - const QStringList &directions() const; - QString toString() const; -private: - QSharedDataPointer<JsonDbSortKeyPrivate> d; -}; -bool operator <(const JsonDbSortKey &a, const JsonDbSortKey &b); - -class JsonDbListModelPrivate; - -class JsonDbListModel : public QAbstractListModel, public QQmlParserStatus -{ - Q_OBJECT - Q_INTERFACES(QQmlParserStatus) -public: - JsonDbListModel(QObject *parent = 0); - virtual ~JsonDbListModel(); - - Q_PROPERTY(QString state READ state NOTIFY stateChanged) - Q_PROPERTY(QString query READ query WRITE setQuery) - Q_PROPERTY(int count READ count NOTIFY countChanged) - Q_PROPERTY(int rowCount READ rowCount NOTIFY rowCountChanged) - Q_PROPERTY(int limit READ limit WRITE setLimit) - Q_PROPERTY(int chunkSize READ chunkSize WRITE setChunkSize) - Q_PROPERTY(int lowWaterMark READ lowWaterMark WRITE setLowWaterMark) - Q_PROPERTY(QVariant roleNames READ scriptableRoleNames WRITE setScriptableRoleNames) - - virtual void classBegin(); - virtual void componentComplete(); - virtual int count() const; - virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; - - virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - virtual QHash<int,QByteArray> roleNames() const; - - virtual void fetchMore(const QModelIndex &parent); - virtual bool canFetchMore(const QModelIndex &parent) const; - - QVariant scriptableRoleNames() const; - void setScriptableRoleNames(const QVariant &roles); - - QString state() const; - - virtual QString toString(int role) const; - int roleFromString(const QString &roleName) const; - - QString query() const; - void setQuery(const QString &newQuery); - - void setLimit(int newLimit); - int limit() const; - - void setChunkSize(int newChunkSize); - int chunkSize() const; - - void setLowWaterMark(int newLowWaterMark); - int lowWaterMark() const; - - Q_INVOKABLE QVariant get(int idx, const QString &property) const; - Q_INVOKABLE void set(int index, const QJSValue &valuemap, - const QJSValue &successCallback = QJSValue(QJSValue::UndefinedValue), - const QJSValue &errorCallback = QJSValue(QJSValue::UndefinedValue)); - Q_INVOKABLE void setProperty(int index, const QString &property, const QVariant &value, - const QJSValue &successCallback = QJSValue(QJSValue::UndefinedValue), - const QJSValue &errorCallback = QJSValue(QJSValue::UndefinedValue)); - Q_INVOKABLE int sectionIndex(const QString §ion, const QJSValue &successCallback = QJSValue(QJSValue::UndefinedValue), - const QJSValue &errorCallback = QJSValue(QJSValue::UndefinedValue)); - -signals: - void needAnotherChunk(int offset) const; - void stateChanged() const; - void countChanged() const; - void rowCountChanged() const; - -private: - Q_DISABLE_COPY(JsonDbListModel) - Q_DECLARE_PRIVATE(JsonDbListModel) - QScopedPointer<JsonDbListModelPrivate> d_ptr; - Q_PRIVATE_SLOT(d_func(), void _q_jsonDbResponse(int, const QVariant&)) - Q_PRIVATE_SLOT(d_func(), void _q_jsonDbErrorResponse(int, int, const QString&)) - Q_PRIVATE_SLOT(d_func(), void _q_jsonDbErrorResponse(int, const QString&)) - Q_PRIVATE_SLOT(d_func(), void _q_jsonDbNotified(const QString&, const QVariant&, const QString&)) - Q_PRIVATE_SLOT(d_func(), void _q_requestAnotherChunk(int)) - -}; -#endif diff --git a/src/imports/jsondb-listmodel/jsondb-listmodel.pro b/src/imports/jsondb-listmodel/jsondb-listmodel.pro deleted file mode 100644 index 870cd03..0000000 --- a/src/imports/jsondb-listmodel/jsondb-listmodel.pro +++ /dev/null @@ -1,20 +0,0 @@ -CXX_MODULE = jsondb -TARGET = jsondblistmodelplugin -TARGETPATH = QtAddOn/JsonDb - -QT += network qml jsondbcompat-private - -HEADERS += \ - jsondb-listmodel.h \ - jsondb-listmodel_p.h \ - jsondb-component.h \ - plugin.h - -SOURCES += \ - jsondb-listmodel.cpp \ - jsondb-component.cpp \ - plugin.cpp - -load(qml_plugin) - -OTHER_FILES += jsondb.json diff --git a/src/imports/jsondb-listmodel/jsondb-listmodel_p.h b/src/imports/jsondb-listmodel/jsondb-listmodel_p.h deleted file mode 100644 index 6035091..0000000 --- a/src/imports/jsondb-listmodel/jsondb-listmodel_p.h +++ /dev/null @@ -1,162 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDBLISTMODEL_P_H -#define JSONDBLISTMODEL_P_H - -#include <QHash> -#include <QMultiMap> -#include <QObject> -#include <QSet> -#include <QStringList> - -#include "jsondb-client.h" -#include "private/jsondb-connection_p.h" - -QT_USE_NAMESPACE_JSONDB - -struct CallbackInfo { - int index; - QJSValue successCallback; - QJSValue errorCallback; -}; - -struct NotifyItem { - QString notifyUuid; - QVariantMap item; - QString action; -}; - -class JsonDbListModelPrivate -{ - Q_DECLARE_PUBLIC(JsonDbListModel) -public: - JsonDbListModel *q_ptr; - int chunkSize; - int lowWaterMark; - int maxCacheSize; - int totalRowCount; - int cacheStart; - int cacheEnd; - int newChunkOffset; - - QSet<int> requestIds; - QSet<int> notificationObjectRequestIds; - QMap<int, CallbackInfo> updateRequestIds; - QMap<int, CallbackInfo> sectionIndexRequestIds; - int totalCountRequestId; - - QHash<QString,QVariantMap> data; // cache that holds all the items. - QMultiMap<JsonDbSortKey,QString> objectUuids; // sort value -> uuid - QMap<QString,JsonDbSortKey> objectSortValues; // uuid -> sort value - QList<QString> cachedUuids; // in the correct sort order. - - QStringList orderDirections; - QStringList orderProperties; - QList<QStringList> orderPaths; - QString query; - QString queryWithoutSort; - - QVariantMap lastFetchedItem; - int lastFetchedIndex; - - bool requestInProgress; - bool componentComplete; - bool resetModel; - bool updateRecieved; - bool totalRowCountRecieved; - - QString notifyUuid; - QVariantMap roleMap; - - QHash<int,QByteArray> roleNames; - QHash<int,QStringList> properties; - QList<NotifyItem> pendingNotifications; - - enum State { - None, - Querying, - Ready - }; - State state; - - JsonDbClient jsonDb; - JsonDbConnection *jsonDbConnection; - -public: - JsonDbListModelPrivate(JsonDbListModel *q); - ~JsonDbListModelPrivate(); - void init(); - void clearCache(int newStart = 0); - int makeSpaceFor(int count, int insertAt); - void removeItem(int index); - int findSortedPosition(const QString& uuid); - JsonDbSortKey sortKey(const QVariantMap &object); - void insertItem(const QVariantMap &item, bool emitCountChanged = true); - void deleteItem(const QVariantMap &item, bool emitCountChanged = true); - void updateItem(const QVariantMap &item); - QVariantMap getItem(int index, bool handleCacheMiss, bool &cacheMiss); - QVariantMap getItem(const QModelIndex &modelIndex, int role, bool handleCacheMiss, bool &cacheMiss); - void set(int index, const QJSValue& valuemap, const QJSValue &successCallback, - const QJSValue &errorCallback); - void setProperty(int index, const QString& property, const QVariant& value, const QJSValue &successCallback, - const QJSValue &errorCallback); - - void fetchChunkSynchronous(int offset); - void updateCache(const QVariantMap &v); - void resetModelFinished(); - - // private slots - void _q_jsonDbResponse(int , const QVariant &); - void _q_jsonDbNotified(const QString&, const QVariant &v, const QString &); - void _q_jsonDbErrorResponse(int , int, const QString&); - void _q_jsonDbErrorResponse(int, const QString&); - - void _q_requestAnotherChunk(int offset); - - void populateModel(); - void createOrUpdateNotification(); - bool findSortOrder(); - - inline int itemsInCache() { return cacheEnd - cacheStart;} -}; - -#endif // JSONDBLISTMODEL_P_H diff --git a/src/imports/jsondb-listmodel/jsondb.json b/src/imports/jsondb-listmodel/jsondb.json deleted file mode 100644 index 0967ef4..0000000 --- a/src/imports/jsondb-listmodel/jsondb.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/src/imports/jsondb-listmodel/plugin.cpp b/src/imports/jsondb-listmodel/plugin.cpp deleted file mode 100644 index 3bee591..0000000 --- a/src/imports/jsondb-listmodel/plugin.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "plugin.h" - -#include "jsondb-client.h" -#include "jsondb-component.h" -#include "jsondb-listmodel.h" - -void JsonDbListModelPlugin::initializeEngine(QQmlEngine *engine, const char *uri) -{ - Q_UNUSED(engine); - Q_UNUSED(uri); -} - -void JsonDbListModelPlugin::registerTypes(const char *uri) -{ - Q_ASSERT(uri == QLatin1String("QtAddOn.JsonDb")); - qmlRegisterType<JsonDbListModel>(uri, 1, 0, "JsonDbListModel"); - qmlRegisterType<JsonDbComponent>(uri, 1, 0, "JsonDb"); -} diff --git a/src/imports/jsondb-listmodel/plugin.h b/src/imports/jsondb-listmodel/plugin.h deleted file mode 100644 index 8d26d8d..0000000 --- a/src/imports/jsondb-listmodel/plugin.h +++ /dev/null @@ -1,58 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDB_PLUGIN_H -#define JSONDB_PLUGIN_H - -#include <QQmlExtensionPlugin> -#include <QtQml/qqml.h> - -class JsonDbListModelPlugin : public QQmlExtensionPlugin -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface" FILE "jsondb.json") - -public: - void initializeEngine(QQmlEngine *engine, const char *uri); - void registerTypes(const char *uri); -}; - -#endif diff --git a/src/imports/jsondb-listmodel/qmldir b/src/imports/jsondb-listmodel/qmldir deleted file mode 100644 index 8edb8dc..0000000 --- a/src/imports/jsondb-listmodel/qmldir +++ /dev/null @@ -1 +0,0 @@ -plugin jsondblistmodelplugin diff --git a/src/src.pro b/src/src.pro index ed85fd2..194bb6f 100644 --- a/src/src.pro +++ b/src/src.pro @@ -1,5 +1,5 @@ TEMPLATE = subdirs CONFIG += ordered -SUBDIRS += 3rdparty jsonstream clientcompat partition client daemon +SUBDIRS += 3rdparty jsonstream partition client daemon !isEmpty(QT.quick.name): SUBDIRS += imports diff --git a/sync.profile b/sync.profile index 72789c2..4207bde 100644 --- a/sync.profile +++ b/sync.profile @@ -1,7 +1,6 @@ %modules = ( # path to module name map "QtJsonDb" => "$basedir/src/client", "QtJsonDbPartition" => "$basedir/src/partition", - "QtJsonDbCompat" => "$basedir/src/clientcompat", ); %moduleheaders = ( # restrict the module headers to those found in relative path ); diff --git a/tests/auto/auto.pro b/tests/auto/auto.pro index 9833156..0fb74f3 100644 --- a/tests/auto/auto.pro +++ b/tests/auto/auto.pro @@ -5,7 +5,6 @@ SUBDIRS = \ partition \ accesscontrol \ qbtree \ - jsondb-listmodel \ jsondblistmodel \ jsondbsortinglistmodel \ jsondbcachinglistmodel \ diff --git a/tests/auto/jsondb-listmodel/jsondb-listmodel.pro b/tests/auto/jsondb-listmodel/jsondb-listmodel.pro deleted file mode 100644 index 364c654..0000000 --- a/tests/auto/jsondb-listmodel/jsondb-listmodel.pro +++ /dev/null @@ -1,26 +0,0 @@ -TARGET = tst_jsondb-listmodel - -QT = core network testlib gui qml jsondbcompat-private -CONFIG -= app_bundle -CONFIG += testcase - -include($$PWD/../../shared/shared.pri) - -DEFINES += JSONDB_DAEMON_BASE=\\\"$$QT.jsondb.bins\\\" -DEFINES += SRCDIR=\\\"$$PWD/\\\" - -INCLUDEPATH += $$PWD/../../../src/imports/jsondb-listmodel -HEADERS += $$PWD/../../../src/imports/jsondb-listmodel/jsondb-listmodel.h -SOURCES += $$PWD/../../../src/imports/jsondb-listmodel/jsondb-listmodel.cpp - -HEADERS += test-jsondb-listmodel.h -SOURCES += test-jsondb-listmodel.cpp - -OTHER_FILES += \ - partitions.json - -data.files = $$OTHER_FILES -data.path = $$[QT_INSTALL_TESTS]/$$TARGET -INSTALLS += data - -DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/jsondb-listmodel/partitions.json b/tests/auto/jsondb-listmodel/partitions.json deleted file mode 100644 index f8a7c87..0000000 --- a/tests/auto/jsondb-listmodel/partitions.json +++ /dev/null @@ -1,3 +0,0 @@ -[ - { "name" :"com.qt-project.shared", "path":".", "default" : true } -] diff --git a/tests/auto/jsondb-listmodel/test-jsondb-listmodel.cpp b/tests/auto/jsondb-listmodel/test-jsondb-listmodel.cpp deleted file mode 100644 index adc8396..0000000 --- a/tests/auto/jsondb-listmodel/test-jsondb-listmodel.cpp +++ /dev/null @@ -1,783 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtTest/QtTest> -#include <QJSEngine> -#include "test-jsondb-listmodel.h" - -#include "../../shared/util.h" -#include <QQmlEngine> -#include <QQmlComponent> -#include <QQmlContext> -#include <QDir> - -ModelData::ModelData(): engine(0), component(0), model(0) -{ -} - -ModelData::~ModelData() -{ - if (model) - delete model; - if (component) - delete component; - if (engine) - delete engine; -} - -TestJsonDbListModel::TestJsonDbListModel() - : mWaitingForNotification(false), mWaitingForDataChange(false), mWaitingForRowsRemoved(false) -{ -} - -TestJsonDbListModel::~TestJsonDbListModel() -{ -} - -void TestJsonDbListModel::deleteDbFiles() -{ - // remove all the test files. - QDir currentDir; - QStringList nameFilter; - nameFilter << QString("*.db"); - nameFilter << "objectFile.bin" << "objectFile2.bin"; - QFileInfoList databaseFiles = currentDir.entryInfoList(nameFilter, QDir::Files); - foreach (QFileInfo fileInfo, databaseFiles) { - //qDebug() << "Deleted : " << fileInfo.fileName(); - QFile file(fileInfo.fileName()); - file.remove(); - } -} - -void TestJsonDbListModel::connectListModel(JsonDbListModel *model) -{ - connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(dataChanged(QModelIndex,QModelIndex))); - connect(model, SIGNAL(modelReset()), this, SLOT(modelReset())); - connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(rowsInserted(QModelIndex,int,int))); - connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(rowsRemoved(QModelIndex,int,int))); - connect(model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), - this, SLOT(rowsMoved(QModelIndex,int,int,QModelIndex,int))); -} - -void TestJsonDbListModel::initTestCase() -{ - // make sure there is no old db files. - deleteDbFiles(); - - QString socketName = QString("testjsondb_%1").arg(getpid()); - mProcess = launchJsonDbDaemon(JSONDB_DAEMON_BASE, socketName, QStringList(), __FILE__); - - mClient = new JsonDbClient(this); - connect(mClient, SIGNAL(notified(QString,QtAddOn::JsonDb::JsonDbNotification)), - this, SLOT(notified(QString,QtAddOn::JsonDb::JsonDbNotification))); - connect( mClient, SIGNAL(response(int, const QVariant&)), - this, SLOT(response(int, const QVariant&))); - connect( mClient, SIGNAL(error(int, int, const QString&)), - this, SLOT(error(int, int, const QString&))); - - QQmlEngine *engine = new QQmlEngine(); - QStringList pluginPaths = engine->importPathList(); - for (int i=0; (i<pluginPaths.count() && mPluginPath.isEmpty()); i++) { - QDir dir(pluginPaths[i]+"/QtAddOn/JsonDb"); - dir.setFilter(QDir::Files | QDir::NoSymLinks); - QFileInfoList list = dir.entryInfoList(); - for (int i = 0; i < list.size(); ++i) { - QList<QQmlError> errors; - if (engine->importPlugin(list.at(i).absoluteFilePath(), QString("QtAddOn.JsonDb"), &errors)) { - mPluginPath = list.at(i).absoluteFilePath(); - break; - } - } - } - delete engine; - -} - -JsonDbListModel *TestJsonDbListModel::createModel() -{ - ModelData *newModel = new ModelData(); - newModel->engine = new QQmlEngine(); - QList<QQmlError> errors; - if (!newModel->engine->importPlugin(mPluginPath, QString("QtAddOn.JsonDb"), &errors)) { - qDebug()<<"Unable to load the plugin :"<<errors; - delete newModel->engine; - return 0; - } - newModel->component = new QQmlComponent(newModel->engine); - newModel->component->setData("import QtQuick 2.0\nimport QtAddOn.JsonDb 1.0 \n JsonDbListModel {id: contactsModel}", QUrl()); - newModel->model = newModel->component->create(); - if (newModel->component->isError()) - qDebug() << newModel->component->errors(); - mModels.append(newModel); - return (JsonDbListModel*)(newModel->model); -} - -void TestJsonDbListModel::deleteModel(JsonDbListModel *model) -{ - for (int i = 0; i < mModels.count(); i++) { - if (mModels[i]->model == model) { - ModelData *modelData = mModels.takeAt(i); - delete modelData; - return; - } - } -} - -void TestJsonDbListModel::cleanupTestCase() -{ - if (mProcess) { - mProcess->kill(); - mProcess->waitForFinished(); - delete mProcess; - } - - deleteDbFiles(); -} - -void TestJsonDbListModel::waitForItemsCreated(int items) -{ - mItemsCreated = 0; - while(mItemsCreated != items) - mEventLoop.processEvents(QEventLoop::AllEvents, mClientTimeout); -} - -void TestJsonDbListModel::waitForExitOrTimeout() -{ - QTimer timer; - QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); - QObject::connect(&timer, SIGNAL(timeout()), &mEventLoop, SLOT(quit())); - timer.start(mClientTimeout); - mElapsedTimer.start(); - mEventLoop.exec(QEventLoop::AllEvents); -} - -// Create items in the model. -void TestJsonDbListModel::createItem() -{ - QVariantMap item; - item.insert("_type", __FUNCTION__); - item.insert("name", "Charlie"); - int id = mClient->create(item); - - waitForResponse1(id); - - JsonDbListModel *listModel = createModel(); - if (!listModel) return; - listModel->setQuery(QString("[?_type=\"%1\"]").arg(__FUNCTION__)); - - QStringList roleNames = (QStringList() << "_type" << "_uuid" << "name"); - listModel->setScriptableRoleNames(roleNames); - connectListModel(listModel); - - // now start it working - listModel->componentComplete(); - QCOMPARE(listModel->count(), 0); - - waitForExitOrTimeout(); - QCOMPARE(listModel->count(), 1); - - mItemsCreated = 0; - item.insert("_type", __FUNCTION__); - item.insert("name", "Baker"); - id = mClient->create(item); - waitForResponse1(id); - if (!mItemsCreated) - waitForExitOrTimeout();; - QCOMPARE(listModel->count(), 2); - deleteModel(listModel); -} - -// Create an item and then update it. -void TestJsonDbListModel::updateItemClient() -{ - QVariantMap item; - item.insert("_type", __FUNCTION__); - item.insert("name", "Charlie"); - int id = mClient->create(item); - waitForResponse1(id); - - JsonDbListModel *listModel = createModel(); - if (!listModel) return; - listModel->setQuery(QString("[?_type=\"%1\"]").arg(__FUNCTION__)); - QStringList roleNames = (QStringList() << "_type" << "_uuid" << "name"); - listModel->setScriptableRoleNames(roleNames); - connectListModel(listModel); - - // now start it working - listModel->componentComplete(); - QCOMPARE(listModel->rowCount(), 0); - - waitForExitOrTimeout(); - QCOMPARE(listModel->rowCount(), 1); - - item.insert("_uuid", mLastUuid); - item.insert("_version", mLastVersion); - item.insert("name", "Baker"); - - mWaitingForDataChange = true; - - id = mClient->update(item); - waitForResponse1(id); - - while (mWaitingForDataChange) - mEventLoop.processEvents(QEventLoop::AllEvents); - - QCOMPARE(listModel->count(), 1); - QCOMPARE(listModel->get(0, "_uuid").toString(), mLastUuid); - QCOMPARE(listModel->get(0, "_type").toString(), QLatin1String(__FUNCTION__)); - QCOMPARE(listModel->get(0, "name").toString(), QLatin1String("Baker")); - deleteModel(listModel); -} - -// Create an item and then update it. -void TestJsonDbListModel::updateItemSet() -{ - QVariantMap item; - item.insert("_type", __FUNCTION__); - item.insert("name", "Charlie"); - item.insert("phone", "123456789"); - int id = mClient->create(item); - waitForResponse1(id); - - JsonDbListModel *listModel = createModel(); - if (!listModel) return; - listModel->setQuery(QString("[?_type=\"%1\"]").arg(__FUNCTION__)); - QStringList roleNames = (QStringList() << "_type" << "_uuid" << "name" << "phone"); - listModel->setScriptableRoleNames(roleNames); - connectListModel(listModel); - - // now start it working - listModel->componentComplete(); - QCOMPARE(listModel->rowCount(), 0); - - waitForExitOrTimeout(); - QCOMPARE(listModel->rowCount(), 1); - - QJSEngine engine; - QJSValue value = engine.newObject(); - - value.setProperty("name", "Baker"); - value.setProperty("phone", "987654321"); - - mWaitingForDataChange = true; - - listModel->set(0,value); - - while (mWaitingForDataChange) - mEventLoop.processEvents(QEventLoop::AllEvents); - - QCOMPARE(listModel->count(), 1); - QCOMPARE(listModel->get(0, "_type").toString(), QLatin1String(__FUNCTION__)); - QCOMPARE(listModel->get(0, "name").toString(), QLatin1String("Baker")); - QCOMPARE(listModel->get(0, "phone").toString(), QLatin1String("987654321")); - deleteModel(listModel); -} - -void TestJsonDbListModel::updateItemSetProperty() -{ - QVariantMap item; - item.insert("_type", __FUNCTION__); - item.insert("name", "Charlie"); - item.insert("phone", "123456789"); - int id = mClient->create(item); - waitForResponse1(id); - - JsonDbListModel *listModel = createModel(); - if (!listModel) return; - listModel->setQuery(QString("[?_type=\"%1\"]").arg(__FUNCTION__)); - QStringList roleNames = (QStringList() << "_type" << "_uuid" << "name" << "phone"); - listModel->setScriptableRoleNames(roleNames); - connectListModel(listModel); - - // now start it working - listModel->componentComplete(); - QCOMPARE(listModel->rowCount(), 0); - - waitForExitOrTimeout(); - QCOMPARE(listModel->rowCount(), 1); - - mWaitingForDataChange = true; - - listModel->setProperty(0,"phone","987654321"); - - while (mWaitingForDataChange) - mEventLoop.processEvents(QEventLoop::AllEvents); - - QCOMPARE(listModel->count(), 1); - QCOMPARE(listModel->get(0, "_type").toString(), QLatin1String(__FUNCTION__)); - QCOMPARE(listModel->get(0, "name").toString(), QLatin1String("Charlie")); - QCOMPARE(listModel->get(0, "phone").toString(), QLatin1String("987654321")); - deleteModel(listModel); -} - -void TestJsonDbListModel::deleteItem() -{ - QVariantMap item; - item.insert("_type", __FUNCTION__); - item.insert("name", "Charlie"); - int id = mClient->create(item); - waitForResponse1(id); - - JsonDbListModel *listModel = createModel(); - if (!listModel) return; - listModel->setQuery(QString("[?_type=\"%1\"]").arg(__FUNCTION__)); - QStringList roleNames = (QStringList() << "_type" << "_uuid" << "name"); - listModel->setScriptableRoleNames(roleNames); - connectListModel(listModel); - - // now start it working - listModel->componentComplete(); - waitForExitOrTimeout(); - QCOMPARE(listModel->rowCount(), 1); - - mItemsCreated = 0; - item.insert("name", "Baker"); - id = mClient->create(item); - waitForResponse1(id); - if (!mItemsCreated) - waitForExitOrTimeout();; - QCOMPARE(listModel->rowCount(), 2); - - mWaitingForRowsRemoved = true; - item.insert("_uuid", mLastUuid); - item.insert("_version", mLastVersion); - id = mClient->remove(item); - waitForResponse1(id); - while(mWaitingForRowsRemoved) - mEventLoop.processEvents(QEventLoop::AllEvents); - - QCOMPARE(listModel->rowCount(), 1); - QCOMPARE(listModel->get(0, "_type").toString(), QLatin1String(__FUNCTION__)); - QCOMPARE(listModel->get(0, "name").toString(), QLatin1String("Charlie")); - deleteModel(listModel); -} - -void TestJsonDbListModel::sortedQuery() -{ - int id = 0; - - QVariantMap index; - index.insert("_type", "Index"); - index.insert("name", "number"); - index.insert("propertyName", "number"); - index.insert("propertyType", "number"); - id = mClient->create(index); - waitForResponse1(id); - - for (int i = 0; i < 1000; i++) { - QVariantMap item; - item.insert("_type", "RandNumber"); - item.insert("number", i); - id = mClient->create(item); - waitForResponse1(id); - } - - JsonDbListModel *listModel = createModel(); - if (!listModel) return; - - connectListModel(listModel); - - QStringList rolenames; - rolenames << "_uuid" << "_type" << "number"; - listModel->setScriptableRoleNames(rolenames); - - listModel->setQuery("[?_type=\"RandNumber\"][/number]"); - - waitForExitOrTimeout(); - QCOMPARE(listModel->count(), 1000); - for (int i = 0; i < 1000; i++) - QCOMPARE(listModel->get(i,"number").toInt(), i); - - listModel->setQuery("[?_type=\"RandNumber\"][\\number]"); - waitForExitOrTimeout(); - for (int i = 0; i < 1000; i++) - QCOMPARE(listModel->get(i,"number").toInt(), 999-i); - - QCoreApplication::instance()->processEvents(); - deleteModel(listModel); -} - -void TestJsonDbListModel::ordering() -{ - for (int i = 9; i >= 1; --i) { - QVariantMap item; - item.insert("_type", __FUNCTION__); - item.insert("name", "Charlie"); - item.insert("order", QString::number(i)); - int id = mClient->create(item); - waitForResponse1(id); - } - - JsonDbListModel *listModel = createModel(); - if (!listModel) return; - listModel->setQuery(QString("[?_type=\"%1\"][/order]").arg(__FUNCTION__)); - QStringList roleNames = (QStringList() << "_type" << "_uuid" << "_version" << "name" << "order"); - listModel->setScriptableRoleNames(roleNames); - connectListModel(listModel); - - // now start it working - listModel->componentComplete(); - QCOMPARE(listModel->rowCount(), 0); - - waitForExitOrTimeout(); - - QStringList expectedOrder = QStringList() << "1" << "2" << "3" << "4" << - "5" << "6" << "7" << "8" << "9"; - QCOMPARE(getOrderValues(listModel), expectedOrder); - mWaitingForDataChange = true; - { - QVariant uuid = listModel->get(4, "_uuid"); - QVERIFY(!uuid.toString().isEmpty()); - QVariant version = listModel->get(4, "_version"); - QVERIFY(!version.toString().isEmpty()); - - QVariantMap item; - item.insert("_uuid", uuid); - item.insert("_version", version); - item.insert("_type", __FUNCTION__); - item.insert("name", "Charlie"); - item.insert("order", "99"); // move it to the end - int id = mClient->update(item); - waitForResponse1(id); - } - - while (mWaitingForDataChange) - mEventLoop.processEvents(QEventLoop::AllEvents); - - expectedOrder = QStringList() << "1" << "2" << "3" << - "4" << "6" << "7" << "8" << "9" << "99"; - QCOMPARE(getOrderValues(listModel), expectedOrder); - mWaitingForDataChange = true; - { - QVariant uuid = listModel->get(8, "_uuid"); - QVERIFY(!uuid.toString().isEmpty()); - QVariant version = listModel->get(8, "_version"); - QVERIFY(!version.toString().isEmpty()); - - QVariantMap item; - item.insert("_uuid", uuid); - item.insert("_version", version); - item.insert("_type", __FUNCTION__); - item.insert("name", "Charlie"); - item.insert("order", "22"); // move it after "2" - int id = mClient->update(item); - waitForResponse1(id); - } - - while (mWaitingForDataChange) - mEventLoop.processEvents(QEventLoop::AllEvents); - - expectedOrder = QStringList() << "1" << "2" << "22" << "3" << - "4" << "6" << "7" << "8" << "9"; - QCOMPARE(getOrderValues(listModel), expectedOrder); - mWaitingForDataChange = true; - { - QVariant uuid = listModel->get(5, "_uuid"); - QVERIFY(!uuid.toString().isEmpty()); - QVariant version = listModel->get(5, "_version"); - QVERIFY(!version.toString().isEmpty()); - - QVariantMap item; - item.insert("_uuid", uuid); - item.insert("_version", version); - item.insert("_type", __FUNCTION__); - item.insert("name", "Charlie"); - item.insert("order", "0"); // move it to the beginning - int id = mClient->update(item); - waitForResponse1(id); - } - - while (mWaitingForDataChange) - mEventLoop.processEvents(QEventLoop::AllEvents); - - expectedOrder = QStringList() << "0" << "1" << "2" << "22" << "3" << - "4" << "7" << "8" << "9"; - QCOMPARE(getOrderValues(listModel), expectedOrder); - deleteModel(listModel); - -} - -void TestJsonDbListModel::itemNotInCache() -{ - QVariantMap index; - index.insert("_type", "Index"); - index.insert("name", "order"); - index.insert("propertyName", "order"); - index.insert("propertyType", "number"); - int indexId = mClient->create(index); - waitForResponse1(indexId); - - QVariantList itemList; - for (int i = 0; i < 1000; i++) { - QVariantMap item; - item.insert("_type", __FUNCTION__); - item.insert("name", "Number"); - item.insert("order", i); - itemList << item; - } - int id = mClient->create(itemList); - waitForResponse1(id); - - JsonDbListModel *listModel = createModel(); - if (!listModel) return; - connectListModel(listModel); - listModel->setLimit(80); - listModel->setQuery(QString("[?_type=\"%1\"][/order]").arg(__FUNCTION__)); - QStringList roleNames = (QStringList() << "_type" << "_uuid" << "name" << "order"); - listModel->setScriptableRoleNames(roleNames); - listModel->componentComplete(); - waitForExitOrTimeout(); - - QCOMPARE(listModel->rowCount(), 1000); - - // Make sure that the first items in the list is in the cache. - QVariant result = listModel->data(listModel->index(10,0), listModel->roleFromString("order")); - QVERIFY(result.isValid()); - QCOMPARE(result.toInt(), 10); - // This item should not be in the cache now. - QVariant res = listModel->data(listModel->index(960,0), listModel->roleFromString("order")); - QCOMPARE(res.toInt(), 960); - deleteModel(listModel); -} - -void TestJsonDbListModel::roles() -{ - QVariantMap item; - item.insert("_type", __FUNCTION__); - item.insert("name", "Charlie"); - item.insert("phone", "123456789"); - int id = mClient->create(item); - - waitForResponse1(id); - - JsonDbListModel *listModel = createModel(); - if (!listModel) return; - listModel->setQuery(QString("[?_type=\"%1\"]").arg(__FUNCTION__)); - - QStringList roleNames = (QStringList() << "_type" << "_uuid" << "name" << "phone"); - listModel->setScriptableRoleNames(roleNames); - connectListModel(listModel); - - // now start it working - listModel->componentComplete(); - waitForExitOrTimeout(); - QCOMPARE(listModel->count(), 1); - - QVariantMap roles = listModel->scriptableRoleNames().toMap(); - QCOMPARE(roles.size(), 4); - QVERIFY(roles.contains("name")) ; - QVERIFY(roles.contains("phone")); - QCOMPARE(listModel->roleFromString("_type"), 0); - QCOMPARE(listModel->roleFromString("_uuid"), 1); - QCOMPARE(listModel->roleFromString("name"), 2); - QCOMPARE(listModel->roleFromString("phone"), 3); - QCOMPARE(listModel->toString(0), QLatin1String("_type")); - QCOMPARE(listModel->toString(1), QLatin1String("_uuid")); - QCOMPARE(listModel->toString(2), QLatin1String("name")); - QCOMPARE(listModel->toString(3), QLatin1String("phone")); - QCOMPARE(listModel->toString(4), QLatin1String("")); - deleteModel(listModel); -} - -void TestJsonDbListModel::totalRowCount() -{ - int id = 0; - QVariantList insertedItems; - for (int i = 0; i < 10; i++) { - QVariantMap item; - item.insert("_type", __FUNCTION__); - item.insert("order", i); - id = mClient->create(item); - waitForResponse1(id); - insertedItems << mData; - } - - JsonDbListModel *listModel = createModel(); - if (!listModel) - return; - connectListModel(listModel); - - listModel->setLimit(10); - listModel->setQuery(QString("[?_type=\"%1\"]").arg(__FUNCTION__)); - QStringList roleNames = (QStringList() << "_type" << "_uuid" << "order"); - listModel->setScriptableRoleNames(roleNames); - listModel->componentComplete(); - waitForExitOrTimeout(); - - QCOMPARE(listModel->rowCount(), 10); - - for (int i = 10; i < 50; i++) { - QVariantMap item; - item.insert("_type", __FUNCTION__); - item.insert("order", i); - mClient->create(item); - } - - waitForItemsCreated(40); - QCOMPARE(listModel->rowCount(), 50); - - // Change query - listModel->setQuery(QString("[?_type=\"%1\"][\\order]").arg(__FUNCTION__)); - waitForExitOrTimeout(); - - QCOMPARE(listModel->rowCount(), 50); - - // Delete the first 10 items - foreach (QVariant item, insertedItems) { - mWaitingForRowsRemoved = true; - id = mClient->remove(item.toMap()); - while(mWaitingForRowsRemoved) - mEventLoop.processEvents(QEventLoop::AllEvents); - } - - QCOMPARE(listModel->rowCount(), 40); - - deleteModel(listModel); -} - -void TestJsonDbListModel::listProperty() -{ - QVariant jsonData = readJsonFile(findFile("list-objects.json")).toVariant(); - QVariantList itemList = jsonData.toList(); - int id = 0; - for (int i = 0; i < itemList.count(); i++) { - id = mClient->create(itemList[i].toMap()); - waitForResponse1(id); - } - - JsonDbListModel *listModel = createModel(); - if (!listModel) - return; - connectListModel(listModel); - QString type = itemList[0].toMap()["_type"].toString(); - listModel->setLimit(10); - listModel->setQuery(QString("[?_type=\"%1\"][/features.0.properties.0.description]").arg(type)); - QStringList roleNames = (QStringList() << "_type" << "_uuid" << "features.0.properties.0.description"<< "features.0.feature"); - listModel->setScriptableRoleNames(roleNames); - listModel->componentComplete(); - waitForExitOrTimeout(); - - QCOMPARE(listModel->count(), itemList.count()); - QCOMPARE(listModel->get(0, "_type").toString(), type); - QCOMPARE(listModel->get(0, "features.0.properties.0.description").toString(), QLatin1String("Facebook account provider")); - QCOMPARE(listModel->get(0, "features.0.feature").toString(), QLatin1String("provide Facebook")); - QCOMPARE(listModel->get(1, "_uuid").toString(), mLastUuid); - QCOMPARE(listModel->get(1, "_type").toString(), type); - QCOMPARE(listModel->get(1, "features.0.properties.0.description").toString(), QLatin1String("Gmail account provider")); - QCOMPARE(listModel->get(1, "features.0.feature").toString(), QLatin1String("provide Gmail")); - - deleteModel(listModel); - - listModel = createModel(); - if (!listModel) - return; - connectListModel(listModel); - type = itemList[0].toMap()["_type"].toString(); - listModel->setLimit(10); - listModel->setQuery(QString("[?_type=\"%1\"][/features.0.properties.0.description]").arg(type)); - roleNames.clear(); - roleNames = (QStringList() << "_type" << "_uuid" << "features[0].properties[0].description"<< "features[0].supported[0]"); - listModel->setScriptableRoleNames(roleNames); - listModel->componentComplete(); - waitForExitOrTimeout(); - - QCOMPARE(listModel->count(), itemList.count()); - QCOMPARE(listModel->get(0, "_type").toString(), type); - QCOMPARE(listModel->get(0, "features[0].properties[0].description").toString(), QLatin1String("Facebook account provider")); - QCOMPARE(listModel->get(0, "features[0].supported[0]").toString(), QLatin1String("share")); - QCOMPARE(listModel->get(1, "_type").toString(), type); - QCOMPARE(listModel->get(1, "features[0].properties[0].description").toString(), QLatin1String("Gmail account provider")); - QCOMPARE(listModel->get(1, "features[0].supported[0]").toString(), QLatin1String("share")); - - deleteModel(listModel); -} - - -QStringList TestJsonDbListModel::getOrderValues(const JsonDbListModel *listModel) -{ - QStringList vals; - for (int i = 0; i < listModel->count(); ++i) - vals << listModel->get(i, "order").toString(); - - return vals; -} - -void TestJsonDbListModel::modelReset() -{ - //qDebug() << "TestJsonDbListModel::modelReset"; - mEventLoop.exit(0); -} -void TestJsonDbListModel::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) -{ - Q_UNUSED(topLeft); - Q_UNUSED(bottomRight); - //qDebug() << "TestJsonDbListModel::dataChanged"; - mWaitingForDataChange = false; -} -void TestJsonDbListModel::rowsInserted(const QModelIndex &parent, int first, int last) -{ - Q_UNUSED(parent); - Q_UNUSED(first); - Q_UNUSED(last); - mItemsCreated++; - //qDebug() << "TestJsonDbListModel::rowsInserted"; - mEventLoop.exit(0); -} -void TestJsonDbListModel::rowsRemoved(const QModelIndex &parent, int first, int last) -{ - Q_UNUSED(parent); - Q_UNUSED(first); - Q_UNUSED(last); - mWaitingForRowsRemoved = false; - //qDebug() << "TestJsonDbListModel::rowsRemoved"; -} -void TestJsonDbListModel::rowsMoved( const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row ) -{ - Q_UNUSED(parent); - Q_UNUSED(start); - Q_UNUSED(end); - Q_UNUSED(destination); - Q_UNUSED(row); - //qDebug() << "TestJsonDbListModel::rowsMoved"; -} - -QTEST_MAIN(TestJsonDbListModel) - diff --git a/tests/auto/jsondb-listmodel/test-jsondb-listmodel.h b/tests/auto/jsondb-listmodel/test-jsondb-listmodel.h deleted file mode 100644 index d9ed276..0000000 --- a/tests/auto/jsondb-listmodel/test-jsondb-listmodel.h +++ /dev/null @@ -1,131 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ -#ifndef TestJsonDbListModel_H -#define TestJsonDbListModel_H - -#include <QCoreApplication> -#include <QList> -#include <QTest> -#include <QFile> -#include <QProcess> -#include <QEventLoop> -#include <QDebug> -#include <QLocalSocket> -#include <QTimer> - -#include <jsondb-client.h> -#include <jsondb-error.h> - -#include "jsondb-listmodel.h" -#include "clientwrapper.h" - -QT_BEGIN_NAMESPACE -class QQmlEngine; -class QQmlComponent; -QT_END_NAMESPACE - -QT_USE_NAMESPACE_JSONDB - -class JsonDbListModel; - -class ModelData { -public: - ModelData(); - ~ModelData(); - QQmlEngine *engine; - QQmlComponent *component; - QObject *model; -}; - -class TestJsonDbListModel: public ClientWrapper -{ - Q_OBJECT -public: - TestJsonDbListModel(); - ~TestJsonDbListModel(); - - void deleteDbFiles(); - void connectListModel(JsonDbListModel *model); - -public slots: - void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight); - void rowsInserted(const QModelIndex &parent, int first, int last); - void rowsRemoved(const QModelIndex &parent, int first, int last); - void rowsMoved( const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row ); - void modelReset(); - -private slots: - void initTestCase(); - void cleanupTestCase(); - - void createItem(); - void updateItemClient(); - void updateItemSet(); - void updateItemSetProperty(); - void deleteItem(); - void sortedQuery(); - void ordering(); - void itemNotInCache(); - void roles(); - void totalRowCount(); - void listProperty(); - -private: - void waitForExitOrTimeout(); - void waitForItemsCreated(int items); - QStringList getOrderValues(const JsonDbListModel *listModel); - JsonDbListModel *createModel(); - void deleteModel(JsonDbListModel *model); - -private: - QProcess *mProcess; - QStringList mNotificationsReceived; - QList<ModelData*> mModels; - QString mPluginPath; - - // Response values - int mItemsCreated; - bool mWaitingForNotification; - bool mWaitingForDataChange; - bool mWaitingForRowsRemoved; -}; - -#endif diff --git a/tests/json.qrc b/tests/json.qrc index dc8a0d3..cd52bf8 100644 --- a/tests/json.qrc +++ b/tests/json.qrc @@ -2,7 +2,7 @@ <qresource prefix="/json"> <file alias="create-test.json">auto/client/create-test.json</file> <file alias="client">auto/client/json</file> - <file alias="list-objects.json">auto/jsondb-listmodel/list-objects.json</file> + <file alias="list-objects.json">shared/json/list-objects.json</file> <file>auto/jsondblistmodel/list-objects.json</file> <file>auto/jsondbsortinglistmodel/list-objects.json</file> <file alias="dataset.json">auto/queries/dataset.json</file> diff --git a/tests/shared/clientwrapper.cpp b/tests/shared/clientwrapper.cpp deleted file mode 100644 index a23942b..0000000 --- a/tests/shared/clientwrapper.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "clientwrapper.h" diff --git a/tests/shared/clientwrapper.h b/tests/shared/clientwrapper.h deleted file mode 100644 index 5883a8c..0000000 --- a/tests/shared/clientwrapper.h +++ /dev/null @@ -1,229 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Digia gives you certain additional -** rights. These rights are described in the Digia Qt LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef CLIENTWRAPPER_H -#define CLIENTWRAPPER_H - -#include <QEventLoop> -#include <QElapsedTimer> -#include <QDebug> -#include <QJsonObject> -#include <QJsonArray> -#include <QJsonValue> -#include <QJsonDocument> - -#include "jsondb-client.h" - -QT_USE_NAMESPACE_JSONDB - -#define waitForResponse(eventloop, result, id_, code, notificationId, count) \ -{ \ - int givenid_ = (id_); \ - (result)->mNotificationId = QVariant(); \ - (result)->mNeedId = (givenid_ != -1); \ - (result)->mId = QVariant(); \ - (result)->mMessage = QString(); \ - (result)->mCode = -1; \ - (result)->mData = QVariant(); \ - (result)->mNotificationWaitCount = count; \ - (result)->mLastUuid = QString(); \ - \ - QTimer timer; \ - QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); \ - QObject::connect(&timer, SIGNAL(timeout()), &eventloop, SLOT(quit())); \ - timer.start(mClientTimeout); \ - mElapsedTimer.start(); \ - do { \ - eventloop.exec(QEventLoop::AllEvents); \ - } while ((result)->mNeedId && (result)->mId.toInt() < QVariant(givenid_).toInt()); \ - if (debug_output) { \ - qDebug() << "waitForResponse" << "expected id" << givenid_ << "got id" << (result)->mId; \ - qDebug() << "waitForResponse" << "expected code" << int(code) << "got code" << (result)->mCode; \ - qDebug() << "waitForResponse" << "expected notificationId" << notificationId << "got notificationId" << (result)->mNotificationId; \ - } \ - if ((result)->mNeedId) QVERIFY2(!(result)->mId.isNull(), "Failed to receive an answer from the db server"); \ - if ((result)->mNeedId) QCOMPARE((result)->mId, QVariant(givenid_)); \ - if ((result)->mNotificationId != QVariant(notificationId)) { \ - if ((result)->mNotificationId.isNull()) { \ - QVERIFY2(false, "we expected notification but did not get it :("); \ - } else { \ - QJsonValue value = QJsonValue::fromVariant((result)->mNotifications.last().mObject); \ - QString data = QString::fromUtf8(value.isArray() ? QJsonDocument(value.toArray()).toJson() : QJsonDocument(value.toObject()).toJson()); \ - QByteArray ba = QString("we didn't expect notification but got it. %1").arg(data).toLatin1(); \ - QVERIFY2(false, ba.constData()); \ - } \ - } \ - QCOMPARE((result)->mNotificationId, QVariant(notificationId)); \ - if ((result)->mCode != int(code)) \ - qDebug() << (result)->mMessage; \ - QCOMPARE((result)->mCode, int(code)); \ -} -#define waitForResponse1(id) waitForResponse(mEventLoop, this, id, -1, QVariant(), 0) -#define waitForResponse2(id, code) waitForResponse(mEventLoop, this, id, code, QVariant(), 0) -#define waitForResponse3(id, code, notificationId) waitForResponse(mEventLoop, this, id, code, notificationId, 0) -#define waitForResponse4(id, code, notificationId, count) waitForResponse(mEventLoop, this, id, code, notificationId, count) - -#define waitForCallbackGeneric(eventloop) \ -{ \ - QTimer timer; \ - QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); \ - QObject::connect(&timer, SIGNAL(timeout()), &eventloop, SLOT(quit())); \ - timer.start(mClientTimeout); \ - mElapsedTimer.start(); \ - mTimedOut = false;\ - callbackError = false; \ - eventloop.exec(QEventLoop::AllEvents); \ - QCOMPARE(false, mTimedOut); \ -} - -#define waitForCallback() waitForCallbackGeneric(mEventLoop) -#define waitForCallback2() waitForCallbackGeneric(mEventLoop2) - -class JsonDbTestNotification -{ -public: - JsonDbTestNotification(const QString ¬ifyUuid, const QVariant &object, const QString &action) - : mNotifyUuid(notifyUuid), mObject(object), mAction(action) {} - - QString mNotifyUuid; - QVariant mObject; - QString mAction; -}; - -class ClientWrapper : public QObject -{ - Q_OBJECT -public: - ClientWrapper(QObject *parent = 0) - : QObject(parent), debug_output(false) - , mClient(0), mCode(0), mNeedId(false), mNotificationWaitCount(0), mClientTimeout(20000) - { - if (qgetenv("JSONDB_CLIENT_TIMEOUT").size()) - mClientTimeout = QString::fromLatin1(qgetenv("JSONDB_CLIENT_TIMEOUT")).toLong(); - } - - void connectToServer() - { - mClient = new QT_PREPEND_NAMESPACE_JSONDB(JsonDbClient)(this); - connect(mClient, SIGNAL(response(int,QVariant)), - this, SLOT(response(int,QVariant))); - connect(mClient, SIGNAL(error(int,int,QString)), - this, SLOT(error(int,int,QString))); - connect(mClient, SIGNAL(notified(QString,QtAddOn::JsonDb::JsonDbNotification)), - this, SLOT(notified(QString,QtAddOn::JsonDb::JsonDbNotification))); - } - - QString addNotification(JsonDbClient::NotifyTypes types, const QString &query, const QString &partition = QString()) { - QEventLoop ev; - QString uuid = mClient->registerNotification(types, query, partition, 0, 0, &ev, SLOT(quit())); - ev.exec(); - return uuid; - } - - bool debug_output; - - QT_PREPEND_NAMESPACE_JSONDB(JsonDbClient) *mClient; - - QEventLoop mEventLoop; - QString mMessage; - int mCode; - bool mNeedId; - QVariant mId, mData, mNotificationId; - QString mLastUuid, mLastVersion; - int mNotificationWaitCount; - QList<JsonDbTestNotification> mNotifications; - quint32 mClientTimeout; - QElapsedTimer mElapsedTimer; - -protected slots: - virtual void notified(const QString ¬ifyUuid, const QtAddOn::JsonDb::JsonDbNotification ¬ification) - { - if (debug_output) - qDebug() << "notified" << notifyUuid << notification.action() << endl << notification.object(); - mNotificationId = notifyUuid; - QString action; - switch (notification.action()) { - case QT_PREPEND_NAMESPACE_JSONDB(JsonDbClient)::NotifyCreate: action = QLatin1String("create"); break; - case QT_PREPEND_NAMESPACE_JSONDB(JsonDbClient)::NotifyUpdate: action = QLatin1String("update"); break; - case QT_PREPEND_NAMESPACE_JSONDB(JsonDbClient)::NotifyRemove: action = QLatin1String("remove"); break; - } - - mNotifications << JsonDbTestNotification(notifyUuid, notification.object(), action); - mNotificationWaitCount -= 1; - if (mId.isValid() && !mNotificationWaitCount) - mEventLoop.quit(); - if (!mNeedId && !mNotificationWaitCount) - mEventLoop.quit(); - } - - virtual void response(int id, const QVariant &data) - { - if (debug_output) - qDebug() << "response" << id << endl << data; - mId = id; - mData = data; - mLastUuid = data.toMap().value("_uuid").toString(); - mLastVersion = data.toMap().value("_version").toString(); - if (mId.isValid() && !mNotificationWaitCount) - mEventLoop.quit(); - if (!mNeedId && !mNotificationWaitCount) - mEventLoop.quit(); - } - - virtual void error(int id, int code, const QString &message) - { - if (debug_output) - qDebug() << "response" << id << code << message; - mId = id; - mCode = code; - mMessage = message; - mEventLoop.quit(); - } - virtual void disconnected() - { - } - virtual void timeout() - { - qDebug() << "timeout" << mElapsedTimer.elapsed(); - } -}; - -#endif // CLIENTWRAPPER_H diff --git a/tests/auto/jsondb-listmodel/list-objects.json b/tests/shared/json/list-objects.json index 79f59fb..79f59fb 100644 --- a/tests/auto/jsondb-listmodel/list-objects.json +++ b/tests/shared/json/list-objects.json diff --git a/tests/shared/shared.pri b/tests/shared/shared.pri index 28a7544..05aba85 100644 --- a/tests/shared/shared.pri +++ b/tests/shared/shared.pri @@ -6,13 +6,8 @@ HEADERS += \ $$PWD/util.h \ $$PWD/qmltestutil.h -contains(QT, jsondbcompat|jsondbcompat-private) { - HEADERS += $$PWD/clientwrapper.h - SOURCES += $$PWD/clientwrapper.cpp -} else { - HEADERS += $$PWD/testhelper.h - SOURCES += $$PWD/testhelper.cpp -} +HEADERS += $$PWD/testhelper.h +SOURCES += $$PWD/testhelper.cpp RESOURCES += \ $$PWD/../json.qrc |