summaryrefslogtreecommitdiffstats
path: root/src/partition/jsondbpartition.h
blob: eae6f16dbb510df84409c564f0bdcacfcf9e66a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia 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.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#ifndef JSONDB_PARTITION_H
#define JSONDB_PARTITION_H

#include <QStringList>
#include <QRegExp>
#include <QSet>
#include <QTimer>
#include <QVector>
#include <QPointer>

#include "jsondberrors.h"
#include "jsondbobjectkey.h"
#include "jsondbnotification.h"
#include "jsondbowner.h"
#include "jsondbpartitionglobal.h"
#include "jsondbstat.h"
#include "jsondbschemamanager_p.h"

QT_BEGIN_HEADER

class TestJsonDb;

QT_BEGIN_NAMESPACE_JSONDB_PARTITION

class JsonDbBtree;
class JsonDbOwner;
class JsonDbObjectTable;
class JsonDbIndex;
class JsonDbIndexQuery;
class JsonDbView;

struct JsonDbUpdate {
    JsonDbUpdate(const JsonDbObject &oldObj, const JsonDbObject &newObj, JsonDbNotification::Action act) :
        oldObject(oldObj), newObject(newObj), action(act) { }
    JsonDbUpdate() : action(JsonDbNotification::None) {}
    JsonDbObject oldObject;
    JsonDbObject newObject;
    JsonDbNotification::Action action;
};

typedef QList<JsonDbUpdate> JsonDbUpdateList;

struct JsonDbWriteResult {
    JsonDbWriteResult() : state(0), code(JsonDbError::NoError) { }
    JsonDbObjectList objectsWritten;
    quint32 state;
    JsonDbError::ErrorCode code;
    QString message;
};

class Q_JSONDB_PARTITION_EXPORT JsonDbPartition : public QObject
{
    Q_OBJECT
public:

    enum WriteMode {
        OptimisticWrite,    // write must not introduce a conflict
        ForcedWrite,        // accept write as is (almost no matter what)
        ReplicatedWrite,    // master/master replication, may create obj._meta.conflicts
        ViewObject          // internal for view object
    };

    JsonDbPartition(const QString &filename, const QString &name, JsonDbOwner *owner, QObject *parent = 0);
    ~JsonDbPartition();
    QString filename() const { return mFilename; }
    bool open();
    bool close();
    bool clear();

    bool beginTransaction();
    bool commitTransaction(quint32 stateNumber = 0);
    bool abortTransaction();

    void initIndexes();
    void flushCaches();
    bool addIndex(const QString &indexName,
                  const QString &propertyName,
                  const QString &propertyType = QString("string"),
                  const QStringList &objectTypes = QStringList(),
                  const QString &propertyFunction = QString(),
                  const QString &locale = QString(),
                  const QString &collation = QString(),
                  const QString &casePreference = QString(),
                  Qt::CaseSensitivity caseSensitive = Qt::CaseSensitive);
    bool removeIndex(const QString &indexName, const QString &objectType = QString());

    bool checkQuota(const JsonDbOwner *owner, int size) const;
    bool addToQuota(const JsonDbOwner *owner, int size);

    JsonDbQueryResult queryObjects(const JsonDbOwner *owner, const JsonDbQuery *query, int limit=-1, int offset=0);
    JsonDbWriteResult updateObjects(const JsonDbOwner *owner, const JsonDbObjectList &objects, WriteMode mode = OptimisticWrite, JsonDbUpdateList *changeList = 0);
    JsonDbWriteResult updateObject(const JsonDbOwner *owner, const JsonDbObject &object, WriteMode mode = OptimisticWrite, JsonDbUpdateList *changeList = 0);

    QJsonObject flush();

    JsonDbView *addView(const QString &viewType);
    void removeView(const QString &viewType);
    JsonDbObjectTable *mainObjectTable() const { return mObjectTable; }
    JsonDbObjectTable *findObjectTable(const QString &objectType) const;
    JsonDbView *findView(const QString &objectType) const;

    bool getObject(const QString &uuid, JsonDbObject &object, const QString &objectType = QString()) const;
    bool getObject(const ObjectKey & objectKey, JsonDbObject &object, const QString &objectType = QString()) const;

    GetObjectsResult getObjects(const QString &keyName, const QJsonValue &key, const QString &type = QString(),
                                bool updateViews = true);

    QJsonObject changesSince(quint32 stateNumber, const QSet<QString> &limitTypes = QSet<QString>());

    inline QString name() const { return mPartitionName; }
    inline void setName(const QString &name) { mPartitionName = name; }
    inline JsonDbOwner *defaultOwner() { return mDefaultOwner; }

    void checkIndex(const QString &propertyName);
    bool compact();
    JsonDbStat stat() const;

    QHash<QString, qint64> fileSizes() const;

    // FIXME: copied from JsonDb class.
    // This is the protocol leaking into the lower layers and should be removed
    static void setError(QJsonObject &map, int code, const QString &message);
    static QJsonObject makeError(int code, const QString &message);
    static QJsonObject makeResponse(const QJsonObject &resultmap, const QJsonObject &errormap, bool silent = false);
    static QJsonObject makeErrorResponse(QJsonObject &resultmap, int code, const QString &message, bool silent = false);
    static bool responseIsError(const QJsonObject &responseMap);

public Q_SLOTS:
    void updateView(const QString &objectType, quint32 stateNumber=0);

Q_SIGNALS:
    void objectsUpdated(const JsonDbUpdateList &objects);

protected:
    void initSchemas();

    void timerEvent(QTimerEvent *event);

    bool checkStateConsistency();
    void checkIndexConsistency(JsonDbObjectTable *table, JsonDbIndex *index);

    JsonDbIndexQuery *compileIndexQuery(const JsonDbOwner *owner, const JsonDbQuery *query);
    void compileOrQueryTerm(JsonDbIndexQuery *indexQuery, const QueryTerm &queryTerm);

    void doIndexQuery(const JsonDbOwner *owner, JsonDbObjectList &results, int &limit, int &offset,
                      JsonDbIndexQuery *indexQuery);

    static void sortValues(const JsonDbQuery *query, JsonDbObjectList &results, JsonDbObjectList &joinedResults);

    bool checkCanAddSchema(const JsonDbObject &schema, const JsonDbObject &oldSchema, QString &errorMsg);
    bool checkCanRemoveSchema(const JsonDbObject &schema, QString &errorMsg);
    bool validateSchema(const QString &schemaName, const JsonDbObject &object, QString &errorMsg);
    bool checkNaturalObjectType(const JsonDbObject &object, QString &errorMsg);

    JsonDbError::ErrorCode checkBuiltInTypeValidity(const JsonDbObject &object, const JsonDbObject &oldObject, QString &errorMsg);
    JsonDbError::ErrorCode checkBuiltInTypeAccessControl(bool forCreation, const JsonDbOwner *owner, const JsonDbObject &object,
                                                         const JsonDbObject &oldObject, QString &errorMsg);
    void updateBuiltInTypes(const JsonDbObject &object, const JsonDbObject &oldObject);
    void setSchema(const QString &schemaName, const QJsonObject &schema);
    void removeSchema(const QString &schemaName);
    void updateSchemaIndexes(const QString &schemaName, QJsonObject object, const QStringList &path=QStringList());

private:
    JsonDbObjectTable     *mObjectTable;
    QVector<JsonDbObjectTable *> mTableTransactions;

    QString      mPartitionName;
    QString      mFilename;
    int          mTransactionDepth;
    bool         mTransactionOk;
    QHash<QString,QPointer<JsonDbView> > mViews;
    QSet<QString> mViewTypes;
    JsonDbSchemaManager   mSchemas;
    QRegExp      mWildCardPrefixRegExp;
    int          mMainSyncTimerId;
    int          mIndexSyncTimerId;
    int          mMainSyncInterval;
    int          mIndexSyncInterval;
    JsonDbOwner *mDefaultOwner;

    friend class JsonDbIndexQuery;
    friend class JsonDbObjectTable;
    friend class JsonDbMapDefinition;
    friend class WithTransaction;
    friend class ::TestPartition;
    friend class ::TestJsonDb;
};

class WithTransaction {
public:
    WithTransaction(JsonDbPartition *partition=0, QString name=QString())
        : mPartition(0)
    {
        Q_UNUSED(name)
        if (partition)
            setPartition(partition);
    }

    ~WithTransaction()
    {
        if (mPartition)
            mPartition->commitTransaction();
    }

    void setPartition(JsonDbPartition *partition)
    {
        Q_ASSERT(!mPartition);
        mPartition = partition;
        if (!mPartition->beginTransaction())
            mPartition = 0;
    }
    bool hasBegin() { return mPartition; }
    bool addObjectTable(JsonDbObjectTable *table);

    void abort()
    {
        if (mPartition)
            mPartition->abortTransaction();
        mPartition = 0;
    }

    void commit(quint32 stateNumber = 0)
    {
        if (mPartition)
            mPartition->commitTransaction(stateNumber);
        mPartition = 0;
    }

private:
    JsonDbPartition *mPartition;
};

QJsonValue makeFieldValue(const QJsonValue &value, const QString &type);
Q_JSONDB_PARTITION_EXPORT QByteArray makeForwardKey(const QJsonValue &fieldValue, const ObjectKey &objectKey);
Q_JSONDB_PARTITION_EXPORT int forwardKeyCmp(const QByteArray &ab, const QByteArray &bb);
void forwardKeySplit(const QByteArray &forwardKey, QJsonValue &fieldValue);
void forwardKeySplit(const QByteArray &forwardKey, QJsonValue &fieldValue, ObjectKey &objectKey);
QByteArray makeForwardValue(const ObjectKey &);
void forwardValueSplit(const QByteArray &forwardValue, ObjectKey &objectKey);

QDebug &operator<<(QDebug &, const ObjectKey &);

QT_END_NAMESPACE_JSONDB_PARTITION

QT_END_HEADER

#endif // JSONDB_PARTITION_H