Debian Codegraph @

maz-db/src/MazDB.cpp

raw symbols SCIP
1 /* Copyright (C) 2017 Dan Chapman <[email protected]>
2
3 This file is part of Dekko email client for Ubuntu devices
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of
8 the License or (at your option) version 3
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18 #include "MazDB.h"
19 #include <leveldb/db.h>
20 #include <leveldb/comparator.h>
21 #include <QFileInfo>
22 #include <QDir>
23 #include <qqmlinfo.h>
24 #include <QJsonDocument>
25 #include "MazDBBatch.h"
26 #include "QJsEngineShim.h"
27
28 static QHash<QString, QWeakPointer<leveldb::DB> > s_levelInstances;
29 static QMultiHash<QString, MazDB*> s_mazInstances;
30
31 MazDB::MazDB(QObject *parent) : QObject(parent),
32 m_leveldb(Q_NULLPTR), m_opened(false), m_status(Status::Undefined), m_batch(Q_NULLPTR)
33 {
34 }
35
36 MazDB::MazDB(const QString &filename, QObject *parent) : MazDB(parent)
37 {
38 setFilename(filename);
39 }
40
41 MazDB::~MazDB()
42 {
43 close();
44 }
45
46 QString MazDB::filename() const
47 {
48 return m_filename;
49 }
50
51 bool MazDB::opened() const
52 {
53 return m_opened;
54 }
55
56 MazDB::Status MazDB::open()
57 {
58 // First check it's not already opened
59 if (m_opened) {
60 setStatus(Status::IOError);
61 setErrorString(QStringLiteral("Database already opened"));
62 return m_status;
63 }
64
65 // Next we have to check for any already existing leveldb instances for this filename
66 if (s_levelInstances.contains(m_filename) && !s_levelInstances[m_filename].isNull()) {
67 m_leveldb = s_levelInstances[m_filename].toStrongRef();
68 m_opened = true;
69 emit openedChanged();
70 setStatus(Status::Ok);
71 setErrorString(QString());
72 } else {
73 // So this is the first time we have seen this location
74 // first check the directory exists
75 QFileInfo db(m_filename);
76 if (!db.dir().exists()) {
77 db.dir().mkpath(db.dir().absolutePath());
78 }
79
80 // now lets fire up a leveldb instance
81 leveldb::DB *ldb;
82 leveldb::Options options;
83 options.create_if_missing = m_options.createIfMissing();
84 options.error_if_exists = m_options.errorIfExists();
85 options.compression = static_cast<leveldb::CompressionType>(m_options.compressionType());
86 options.paranoid_checks = m_options.paranoidChecks();
87
88 auto status = leveldb::DB::Open(options, m_filename.toStdString(), &ldb);
89 if (status.ok()) {
90 m_leveldb.reset(ldb);
91 s_levelInstances.insert(m_filename, m_leveldb.toWeakRef());
92 }
93 m_opened = status.ok();
94 emit openedChanged();
95 setErrorString(QString::fromStdString(status.ToString()));
96 Status code = parseStatusCode(status);
97 setStatus(code);
98
99 }
100 if (m_opened) {
101 // add this to the list of current MazDB instances.
102 s_mazInstances.insertMulti(m_filename, this);
103 }
104 return m_status;
105 }
106
107 void MazDB::close()
108 {
109 delete m_batch;
110 m_batch = 0;
111
112 m_leveldb.clear();
113 QWeakPointer<leveldb::DB> pointer = s_levelInstances[m_filename];
114 if (pointer.isNull())
115 s_levelInstances.remove(m_filename);
116
117 for (auto key : s_mazInstances.keys()){
118 s_mazInstances.remove(key, this);
119 }
120 setStatus(Status::Undefined);
121 m_opened = false;
122 emit openedChanged();
123 setErrorString(QString());
124 }
125
126 MazDB::Status MazDB::status() const
127 {
128 return m_status;
129 }
130
131 QString MazDB::errorString() const
132 {
133 return m_errorString;
134 }
135
136 MazOptions *MazDB::options()
137 {
138 return &m_options;
139 }
140
141 MazDBBatch *MazDB::batch()
142 {
143 if (m_batch) {
144 delete m_batch;
145 }
146 m_batch = new MazDBBatch(m_leveldb.toWeakRef(),this);
147 connect(m_batch, &MazDBBatch::batchWritten, this, &MazDB::onBatchWritten);
148 return m_batch;
149 }
150
151 bool MazDB::del(const QString &key)
152 {
153 leveldb::WriteOptions options;
154 leveldb::Status status = m_leveldb.data()->Delete(options, leveldb::Slice(key.toStdString()));
155 if (status.ok()) {
156 emitKeyValueRemoved(key);
157 }
158 return status.ok();
159 }
160
161 QVariant MazDB::get(const QString &key, QVariant defaultValue)
162 {
163 leveldb::ReadOptions options;
164 std::string value = "";
165 if (m_opened && !m_leveldb.isNull()){
166 leveldb::Status status = m_leveldb.data()->Get(options,
167 leveldb::Slice(key.toStdString()),
168 &value);
169 if (status.ok())
170 return MazUtils::jsonToVariant(QString::fromStdString(value));
171 }
172 return defaultValue;
173 }
174
175 bool MazDB::put(const QString &key, const QVariant &value)
176 {
177 QVariant oldValue = get(key);
178 //avoid inifine loops
179 if(oldValue == value)
180 return true;
181 leveldb::WriteOptions options;
182 QString json = MazUtils::variantToJson(value);
183 if (m_opened && m_leveldb){
184 leveldb::Status status = m_leveldb->Put(options,
185 leveldb::Slice(key.toStdString()),
186 leveldb::Slice(json.toStdString()));
187 if(status.ok()){
188 emitPropertyChanged(key, value);
189 }
190 return status.ok();
191 }
192 return false;
193 }
194
195 bool MazDB::putSync(const QString &key, const QVariant &value)
196 {
197 QVariant oldValue = get(key);
198 //avoid inifine loops
199 if(oldValue == value)
200 return true;
201 leveldb::WriteOptions options;
202 QString json = MazUtils::variantToJson(value);
203 options.sync = true;
204 if (m_opened && m_leveldb){
205 leveldb::Status status = m_leveldb->Put(options,
206 leveldb::Slice(key.toStdString()),
207 leveldb::Slice(json.toStdString()));
208 if(status.ok()){
209 emitPropertyChanged(key, value);
210 }
211 return status.ok();
212 }
213 return false;
214 }
215
216 bool MazDB::destroyDB(const QString &filename)
217 {
218 if(m_filename == filename){
219 setFilename(QString());
220 }
221 leveldb::Options options;
222 leveldb::Status status = leveldb::DestroyDB(filename.toStdString(), options);
223 setStatus(parseStatusCode(status));
224 setErrorString(QString::fromStdString(status.ToString()));
225 return m_status == Status::Ok;
226 }
227
228 bool MazDB::repairDB(const QString &filename)
229 {
230 leveldb::Options options;
231 leveldb::Status status = leveldb::RepairDB(filename.toStdString(), options);
232 return status.ok();
233 }
234
235 bool MazDB::readStream(MazCallBack callback, const QString startKey, const int length)
236 {
237 if (!opened() || length == 0)
238 return false;
239
240 int llength = length;
241 leveldb::ReadOptions options;
242 leveldb::Iterator *it = m_leveldb.data()->NewIterator(options);
243
244 if (!it)
245 return false;
246
247 QMutexLocker l(&m_mutex);
248 if (!startKey.isEmpty()) {
249 it->Seek(leveldb::Slice(startKey.toStdString()));
250 } else {
251 it->SeekToFirst();
252 }
253
254 for ( ;it->Valid(); it->Next()){
255
256 QString key = QString::fromStdString(it->key().ToString());
257 QVariant value = MazUtils::jsonToVariant(QString::fromStdString(it->value().ToString()));
258
259 llength--;
260 bool shouldContinue = callback(key, value);
261
262 if (!shouldContinue || (length != -1 && llength <= 0))
263 break;
264 }
265 delete it;
266 return true;
267 }
268
269 bool MazDB::readStream(QJSValue callback, QString startKey, int length)
270 {
271 if (!callback.isCallable())
272 return false;
273
274 MazCallBack func = [this, &callback](QString key, QVariant value) {
275 QJSEngine *engine = qjsEngine(this);
276 QJSValueList list;
277 list << QJSValue(key);
278 list << engine->toScriptValue<QVariant>(value);
279 bool result = callback.call(list).toBool();
280 return result;
281 };
282 return readStream(func, startKey, length);
283 }
284
285 bool MazDB::keyStream(MazKeyCallBack callback, const QString startKey, const int length)
286 {
287 if (!opened() || length == 0)
288 return false;
289
290 int llength = length;
291 leveldb::ReadOptions options;
292 leveldb::Iterator *it = m_leveldb.data()->NewIterator(options);
293
294 if (!it)
295 return false;
296
297 QMutexLocker l(&m_mutex);
298 if (!startKey.isEmpty()) {
299 it->Seek(leveldb::Slice(startKey.toStdString()));
300 } else {
301 it->SeekToFirst();
302 }
303
304 for ( ;it->Valid(); it->Next()){
305
306 QString key = QString::fromStdString(it->key().ToString());
307
308 llength--;
309 bool shouldContinue = callback(key);
310
311 if (!shouldContinue || (length != -1 && llength <= 0))
312 break;
313 }
314 delete it;
315 return true;
316 }
317
318 bool MazDB::keyStream(QJSValue callback, QString startKey, int length)
319 {
320 if (!callback.isCallable())
321 return false;
322
323 MazKeyCallBack func = [this, &callback](QString key) {
324 QJSValueList list;
325 list << QJSValue(key);
326 bool result = callback.call(list).toBool();
327 return result;
328 };
329 return keyStream(func, startKey, length);
330 }
331
332 bool MazDB::valueStream(MazValueCallBack callback, const QString startKey, const int length)
333 {
334 if (!opened() || length == 0)
335 return false;
336
337 int llength = length;
338 leveldb::ReadOptions options;
339 leveldb::Iterator *it = m_leveldb.data()->NewIterator(options);
340
341 if (!it)
342 return false;
343
344 QMutexLocker l(&m_mutex);
345 if (!startKey.isEmpty()) {
346 it->Seek(leveldb::Slice(startKey.toStdString()));
347 } else {
348 it->SeekToFirst();
349 }
350
351 for ( ;it->Valid(); it->Next()){
352
353 QString key = QString::fromStdString(it->key().ToString());
354 QVariant value = MazUtils::jsonToVariant(QString::fromStdString(it->value().ToString()));
355
356 llength--;
357 bool shouldContinue = callback(value);
358
359 if (!shouldContinue || (length != -1 && llength <= 0))
360 break;
361 }
362 delete it;
363 return true;
364 }
365
366 bool MazDB::valueStream(QJSValue callback, QString startKey, int length)
367 {
368 if (!callback.isCallable())
369 return false;
370
371 MazValueCallBack func = [this, &callback](QVariant value) {
372 QJSEngine *engine = qjsEngine(this);
373 QJSValueList list;
374 list << engine->toScriptValue<QVariant>(value);
375 bool result = callback.call(list).toBool();
376 return result;
377 };
378 return valueStream(func, startKey, length);
379 }
380
381 bool MazDB::rangeStream(MazCallBack callback, const QString startKey, const QString endKey)
382 {
383 if (!opened())
384 return false;
385
386 if (startKey.isEmpty() || endKey.isEmpty() || endKey < startKey) {
387 return false;
388 }
389
390 leveldb::Options options;
391 leveldb::Iterator *it = m_leveldb.data()->NewIterator(leveldb::ReadOptions());
392
393 if (!it)
394 return false;
395
396
397 QMutexLocker l(&m_mutex);
398
399 leveldb::Slice startSlice(startKey.toStdString());
400 leveldb::Slice endSlice(endKey.toStdString());
401
402 for (it->Seek(startSlice);
403 it->Valid() && options.comparator->Compare(it->key(), endSlice) <= 0;
404 it->Next()) {
405 QString key = QString::fromStdString(it->key().ToString());
406 QVariant value = MazUtils::jsonToVariant(QString::fromStdString(it->value().ToString()));
407
408 bool shouldContinue = callback(key, value);
409 if (!shouldContinue) {
410 break;
411 }
412 }
413
414 delete it;
415 return true;
416 }
417
418 bool MazDB::rangeStream(QJSValue callback, QString startKey, const QString endKey)
419 {
420 if (!callback.isCallable())
421 return false;
422
423 MazCallBack func = [this, &callback](QString key, QVariant value) {
424 QJSEngine *engine = qjsEngine(this);
425 QJSValueList list;
426 list << QJSValue(key);
427 list << engine->toScriptValue<QVariant>(value);
428 bool result = callback.call(list).toBool();
429 return result;
430 };
431 return rangeStream(func, startKey, endKey);
432 }
433
434 void MazDB::setFilename(const QString &name)
435 {
436 if (name != m_filename) {
437 if (opened()) {
438 close();
439 }
440 m_filename = name;
441 emit filenameChanged();
442 if (!m_filename.isEmpty()) {
443 open();
444 }
445 }
446 }
447
448 void MazDB::onBatchWritten(QSet<QString> keys)
449 {
450 for (auto key : keys){
451 emitPropertyChanged(key, get(key, QVariant()));
452 }
453 }
454
455 void MazDB::setStatus(const MazDB::Status status)
456 {
457 if (status != m_status) {
458 m_status = status;
459 emit statusChanged(m_status);
460 }
461 }
462
463 void MazDB::setErrorString(const QString &errorString)
464 {
465 if (errorString != m_errorString) {
466 m_errorString = errorString;
467 emit errorStringChanged(m_errorString);
468 }
469 }
470
471 MazDB::Status MazDB::parseStatusCode(leveldb::Status &status)
472 {
473 if (status.ok())
474 return Status::Ok;
475 if (status.IsCorruption())
476 return Status::Corruption;
477 if (status.IsIOError())
478 return Status::IOError;
479 if (status.IsNotFound())
480 return Status::NotFound;
481 return Status::Undefined;
482 }
483
484 void MazDB::emitPropertyChanged(const QString &key, const QVariant &value)
485 {
486 QMultiHash<QString, MazDB*>::iterator i = s_mazInstances.find(m_filename);
487 while (i != s_mazInstances.end() && i.key() == m_filename) {
488 emit i.value()->keyValueChanged(key, value);
489 ++i;
490 }
491 }
492
493 void MazDB::emitKeyValueRemoved(const QString &key)
494 {
495 QMultiHash<QString, MazDB*>::iterator i = s_mazInstances.find(m_filename);
496 while (i != s_mazInstances.end() && i.key() == m_filename) {
497 emit i.value()->keyValueRemoved(key);
498 ++i;
499 }
500 }
501
502 void MazDB::classBegin()
503 {
504
505 }
506
507 void MazDB::componentComplete()
508 {
509
510 }
511