| 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 "MazDBBatch.h" |
| 19 | #include <leveldb/db.h> |
| 20 | #include <leveldb/write_batch.h> |
| 21 | #include <leveldb/options.h> |
| 22 | |
| 23 | MazDBBatch::MazDBBatch(QWeakPointer<leveldb::DB> db, QObject *parent) : QObject(parent), |
| 24 | m_leveldb(db), m_batch(new leveldb::WriteBatch()) |
| 25 | { |
| 26 | |
| 27 | } |
| 28 | |
| 29 | MazDBBatch::~MazDBBatch() |
| 30 | { |
| 31 | if (m_batch) { |
| 32 | delete m_batch; |
| 33 | m_batch = Q_NULLPTR; |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | MazDBBatch *MazDBBatch::del(const QString &key) |
| 38 | { |
| 39 | m_keys.insert(key); |
| 40 | QMutexLocker l(&m_mutex); |
| 41 | m_batch->Delete(leveldb::Slice(key.toStdString())); |
| 42 | return this; |
| 43 | } |
| 44 | |
| 45 | MazDBBatch *MazDBBatch::put(const QString &key, const QVariant &value) |
| 46 | { |
| 47 | QString json = MazUtils::variantToJson(value); |
| 48 | m_keys.insert(key); |
| 49 | QMutexLocker l(&m_mutex); |
| 50 | m_batch->Put(leveldb::Slice(key.toStdString()), |
| 51 | leveldb::Slice(json.toStdString())); |
| 52 | return this; |
| 53 | } |
| 54 | |
| 55 | MazDBBatch *MazDBBatch::clear() |
| 56 | { |
| 57 | m_keys.clear(); |
| 58 | QMutexLocker l(&m_mutex); |
| 59 | m_batch->Clear(); |
| 60 | return this; |
| 61 | } |
| 62 | |
| 63 | bool MazDBBatch::write() |
| 64 | { |
| 65 | leveldb::WriteOptions options; |
| 66 | options.sync = true; |
| 67 | if(m_leveldb.isNull()) |
| 68 | return static_cast<int>(MazDB::Status::NotFound); |
| 69 | leveldb::Status status = m_leveldb.data()->Write(options, m_batch); |
| 70 | if(status.ok()){ |
| 71 | emit batchWritten(m_keys); |
| 72 | } |
| 73 | return status.ok(); |
| 74 | } |
| 75 |