summaryrefslogtreecommitdiffstats
path: root/common/queryrunner.cpp
diff options
context:
space:
mode:
authorChristian Mollekopf <chrigi_1@fastmail.fm>2015-11-27 17:30:04 +0100
committerChristian Mollekopf <chrigi_1@fastmail.fm>2015-11-27 17:30:04 +0100
commit5b41b26a349967acf2197f9f9228526193fd826e (patch)
tree166452bcc0757564deefe233bf031d2ccb0564d2 /common/queryrunner.cpp
parent13af56e436f49df32d3b2f6f223cf1dec2eabaac (diff)
downloadsink-5b41b26a349967acf2197f9f9228526193fd826e.tar.gz
sink-5b41b26a349967acf2197f9f9228526193fd826e.zip
Introduced a QueryRunner object
The QueryRunner object lives for the duration of the query (so just for the initial query for non-live queries, and for the lifetime of the result model for live queries). It's supposed to handle all the threading internally and decouple the lifetime of the facade.
Diffstat (limited to 'common/queryrunner.cpp')
-rw-r--r--common/queryrunner.cpp292
1 files changed, 292 insertions, 0 deletions
diff --git a/common/queryrunner.cpp b/common/queryrunner.cpp
new file mode 100644
index 0000000..4159112
--- /dev/null
+++ b/common/queryrunner.cpp
@@ -0,0 +1,292 @@
1/*
2 Copyright (c) 2015 Christian Mollekopf <mollekopf@kolabsys.com>
3
4 This library is free software; you can redistribute it and/or modify it
5 under the terms of the GNU Library General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or (at your
7 option) any later version.
8
9 This library is distributed in the hope that it will be useful, but WITHOUT
10 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
12 License for more details.
13
14 You should have received a copy of the GNU Library General Public License
15 along with this library; see the file COPYING.LIB. If not, write to the
16 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 02110-1301, USA.
18*/
19#include "queryrunner.h"
20
21#include <QtConcurrent/QtConcurrentRun>
22#include <QFuture>
23#include <QFutureWatcher>
24#include "commands.h"
25#include "log.h"
26#include "storage.h"
27#include "definitions.h"
28#include "domainadaptor.h"
29
30using namespace Akonadi2;
31
32static inline ResultSet fullScan(const Akonadi2::Storage::Transaction &transaction, const QByteArray &bufferType)
33{
34 //TODO use a result set with an iterator, to read values on demand
35 QVector<QByteArray> keys;
36 transaction.openDatabase(bufferType + ".main").scan(QByteArray(), [&](const QByteArray &key, const QByteArray &value) -> bool {
37 //Skip internals
38 if (Akonadi2::Storage::isInternalKey(key)) {
39 return true;
40 }
41 keys << Akonadi2::Storage::uidFromKey(key);
42 return true;
43 },
44 [](const Akonadi2::Storage::Error &error) {
45 qWarning() << "Error during query: " << error.message;
46 });
47
48 Trace() << "Full scan found " << keys.size() << " results";
49 return ResultSet(keys);
50}
51
52template<class DomainType>
53QueryRunner<DomainType>::QueryRunner(const Akonadi2::Query &query, const Akonadi2::ResourceAccessInterface::Ptr &resourceAccess, const QByteArray &instanceIdentifier, const DomainTypeAdaptorFactoryInterface::Ptr &factory, const QByteArray &bufferType)
54 : QueryRunnerBase(),
55 mResourceAccess(resourceAccess),
56 mResultProvider(new ResultProvider<typename DomainType::Ptr>),
57 mDomainTypeAdaptorFactory(factory),
58 mQuery(query),
59 mResourceInstanceIdentifier(instanceIdentifier),
60 mBufferType(bufferType)
61{
62 Trace() << "Starting query";
63 //We delegate loading of initial data to the result provider, os it can decide for itself what it needs to load.
64 mResultProvider->setFetcher([this, query](const typename DomainType::Ptr &parent) {
65 Trace() << "Running fetcher";
66
67 // auto watcher = new QFutureWatcher<qint64>;
68 // QObject::connect(watcher, &QFutureWatcher::finished, [](qint64 newRevision) {
69 // mResourceAccess->sendRevisionReplayedCommand(newRevision);
70 // });
71 // auto future = QtConcurrent::run([&resultProvider]() -> qint64 {
72 // const qint64 newRevision = executeInitialQuery(query, parent, resultProvider);
73 // return newRevision;
74 // });
75 // watcher->setFuture(future);
76 const qint64 newRevision = executeInitialQuery(query, parent, *mResultProvider);
77 mResourceAccess->sendRevisionReplayedCommand(newRevision);
78 });
79
80
81 //In case of a live query we keep the runner for as long alive as the result provider exists
82 if (query.liveQuery) {
83 //Incremental updates are always loaded directly, leaving it up to the result to discard the changes if they are not interesting
84 setQuery([this, query] () -> KAsync::Job<void> {
85 return KAsync::start<void>([this, query](KAsync::Future<void> &future) {
86 //TODO execute in thread
87 const qint64 newRevision = executeIncrementalQuery(query, *mResultProvider);
88 mResourceAccess->sendRevisionReplayedCommand(newRevision);
89 future.setFinished();
90 });
91 });
92 //Ensure the connection is open, if it wasn't already opened
93 //TODO If we are not connected already, we have to check for the latest revision once connected, otherwise we could miss some updates
94 mResourceAccess->open();
95 QObject::connect(mResourceAccess.data(), &Akonadi2::ResourceAccess::revisionChanged, this, &QueryRunner::revisionChanged);
96 }
97}
98
99template<class DomainType>
100typename Akonadi2::ResultEmitter<typename DomainType::Ptr>::Ptr QueryRunner<DomainType>::emitter()
101{
102 return mResultProvider->emitter();
103}
104
105//TODO move into result provider?
106template<class DomainType>
107void QueryRunner<DomainType>::replaySet(ResultSet &resultSet, Akonadi2::ResultProviderInterface<typename DomainType::Ptr> &resultProvider)
108{
109 // Trace() << "Replay set";
110 while (resultSet.next([&resultProvider](const Akonadi2::ApplicationDomain::ApplicationDomainType::Ptr &value, Akonadi2::Operation operation) -> bool {
111 switch (operation) {
112 case Akonadi2::Operation_Creation:
113 // Trace() << "Got creation";
114 resultProvider.add(Akonadi2::ApplicationDomain::ApplicationDomainType::getInMemoryRepresentation<DomainType>(*value).template staticCast<DomainType>());
115 break;
116 case Akonadi2::Operation_Modification:
117 // Trace() << "Got modification";
118 resultProvider.modify(Akonadi2::ApplicationDomain::ApplicationDomainType::getInMemoryRepresentation<DomainType>(*value).template staticCast<DomainType>());
119 break;
120 case Akonadi2::Operation_Removal:
121 // Trace() << "Got removal";
122 resultProvider.remove(Akonadi2::ApplicationDomain::ApplicationDomainType::getInMemoryRepresentation<DomainType>(*value).template staticCast<DomainType>());
123 break;
124 }
125 return true;
126 })){};
127}
128
129template<class DomainType>
130void QueryRunner<DomainType>::readEntity(const Akonadi2::Storage::NamedDatabase &db, const QByteArray &key, const std::function<void(const Akonadi2::ApplicationDomain::ApplicationDomainType::Ptr &, Akonadi2::Operation)> &resultCallback)
131{
132 //This only works for a 1:1 mapping of resource to domain types.
133 //Not i.e. for tags that are stored as flags in each entity of an imap store.
134 //additional properties that don't have a 1:1 mapping (such as separately stored tags),
135 //could be added to the adaptor.
136 db.findLatest(key, [=](const QByteArray &key, const QByteArray &value) -> bool {
137 Akonadi2::EntityBuffer buffer(value.data(), value.size());
138 const Akonadi2::Entity &entity = buffer.entity();
139 const auto metadataBuffer = Akonadi2::EntityBuffer::readBuffer<Akonadi2::Metadata>(entity.metadata());
140 Q_ASSERT(metadataBuffer);
141 const qint64 revision = metadataBuffer ? metadataBuffer->revision() : -1;
142 resultCallback(DomainType::Ptr::create(mResourceInstanceIdentifier, Akonadi2::Storage::uidFromKey(key), revision, mDomainTypeAdaptorFactory->createAdaptor(entity)), metadataBuffer->operation());
143 return false;
144 },
145 [](const Akonadi2::Storage::Error &error) {
146 qWarning() << "Error during query: " << error.message;
147 });
148}
149
150template<class DomainType>
151ResultSet QueryRunner<DomainType>::loadInitialResultSet(const Akonadi2::Query &query, Akonadi2::Storage::Transaction &transaction, QSet<QByteArray> &remainingFilters)
152{
153 QSet<QByteArray> appliedFilters;
154 auto resultSet = Akonadi2::ApplicationDomain::TypeImplementation<DomainType>::queryIndexes(query, mResourceInstanceIdentifier, appliedFilters, transaction);
155 remainingFilters = query.propertyFilter.keys().toSet() - appliedFilters;
156
157 //We do a full scan if there were no indexes available to create the initial set.
158 if (appliedFilters.isEmpty()) {
159 //TODO this should be replaced by an index lookup as well
160 resultSet = fullScan(transaction, mBufferType);
161 }
162 return resultSet;
163}
164
165template<class DomainType>
166ResultSet QueryRunner<DomainType>::loadIncrementalResultSet(qint64 baseRevision, const Akonadi2::Query &query, Akonadi2::Storage::Transaction &transaction, QSet<QByteArray> &remainingFilters)
167{
168 const auto bufferType = mBufferType;
169 auto revisionCounter = QSharedPointer<qint64>::create(baseRevision);
170 remainingFilters = query.propertyFilter.keys().toSet();
171 return ResultSet([bufferType, revisionCounter, &transaction]() -> QByteArray {
172 const qint64 topRevision = Akonadi2::Storage::maxRevision(transaction);
173 //Spit out the revision keys one by one.
174 while (*revisionCounter <= topRevision) {
175 const auto uid = Akonadi2::Storage::getUidFromRevision(transaction, *revisionCounter);
176 const auto type = Akonadi2::Storage::getTypeFromRevision(transaction, *revisionCounter);
177 // Trace() << "Revision" << *revisionCounter << type << uid;
178 if (type != bufferType) {
179 //Skip revision
180 *revisionCounter += 1;
181 continue;
182 }
183 const auto key = Akonadi2::Storage::assembleKey(uid, *revisionCounter);
184 *revisionCounter += 1;
185 return key;
186 }
187 Trace() << "Finished reading incremental result set:" << *revisionCounter;
188 //We're done
189 return QByteArray();
190 });
191}
192
193template<class DomainType>
194ResultSet QueryRunner<DomainType>::filterSet(const ResultSet &resultSet, const std::function<bool(const Akonadi2::ApplicationDomain::ApplicationDomainType::Ptr &domainObject)> &filter, const Akonadi2::Storage::NamedDatabase &db, bool initialQuery)
195{
196 auto resultSetPtr = QSharedPointer<ResultSet>::create(resultSet);
197
198 //Read through the source values and return whatever matches the filter
199 std::function<bool(std::function<void(const Akonadi2::ApplicationDomain::ApplicationDomainType::Ptr &, Akonadi2::Operation)>)> generator = [this, resultSetPtr, &db, filter, initialQuery](std::function<void(const Akonadi2::ApplicationDomain::ApplicationDomainType::Ptr &, Akonadi2::Operation)> callback) -> bool {
200 while (resultSetPtr->next()) {
201 //readEntity is only necessary if we actually want to filter or know the operation type (but not a big deal if we do it always I guess)
202 readEntity(db, resultSetPtr->id(), [this, filter, callback, initialQuery](const Akonadi2::ApplicationDomain::ApplicationDomainType::Ptr &domainObject, Akonadi2::Operation operation) {
203 //Always remove removals, they probably don't match due to non-available properties
204 if (filter(domainObject) || operation == Akonadi2::Operation_Removal) {
205 Trace() << "entity is not filtered" << initialQuery;
206 if (initialQuery) {
207 //We're not interested in removals during the initial query
208 if (operation != Akonadi2::Operation_Removal) {
209 callback(domainObject, Akonadi2::Operation_Creation);
210 }
211 } else {
212 callback(domainObject, operation);
213 }
214 }
215 });
216 }
217 return false;
218 };
219 return ResultSet(generator);
220}
221
222
223template<class DomainType>
224std::function<bool(const Akonadi2::ApplicationDomain::ApplicationDomainType::Ptr &domainObject)> QueryRunner<DomainType>::getFilter(const QSet<QByteArray> remainingFilters, const Akonadi2::Query &query)
225{
226 return [remainingFilters, query](const Akonadi2::ApplicationDomain::ApplicationDomainType::Ptr &domainObject) -> bool {
227 for (const auto &filterProperty : remainingFilters) {
228 const auto property = domainObject->getProperty(filterProperty);
229 if (property.isValid()) {
230 //TODO implement other comparison operators than equality
231 if (property != query.propertyFilter.value(filterProperty)) {
232 Trace() << "Filtering entity due to property mismatch: " << domainObject->getProperty(filterProperty);
233 return false;
234 }
235 } else {
236 Warning() << "Ignored property filter because value is invalid: " << filterProperty;
237 }
238 }
239 return true;
240 };
241}
242
243template<class DomainType>
244qint64 QueryRunner<DomainType>::load(const Akonadi2::Query &query, const std::function<ResultSet(Akonadi2::Storage::Transaction &, QSet<QByteArray> &)> &baseSetRetriever, Akonadi2::ResultProviderInterface<typename DomainType::Ptr> &resultProvider, bool initialQuery)
245{
246 Akonadi2::Storage storage(Akonadi2::storageLocation(), mResourceInstanceIdentifier);
247 storage.setDefaultErrorHandler([](const Akonadi2::Storage::Error &error) {
248 Warning() << "Error during query: " << error.store << error.message;
249 });
250 auto transaction = storage.createTransaction(Akonadi2::Storage::ReadOnly);
251 auto db = transaction.openDatabase(mBufferType + ".main");
252
253 QSet<QByteArray> remainingFilters;
254 auto resultSet = baseSetRetriever(transaction, remainingFilters);
255 auto filteredSet = filterSet(resultSet, getFilter(remainingFilters, query), db, initialQuery);
256 replaySet(filteredSet, resultProvider);
257 resultProvider.setRevision(Akonadi2::Storage::maxRevision(transaction));
258 return Akonadi2::Storage::maxRevision(transaction);
259}
260
261
262template<class DomainType>
263qint64 QueryRunner<DomainType>::executeIncrementalQuery(const Akonadi2::Query &query, Akonadi2::ResultProviderInterface<typename DomainType::Ptr> &resultProvider)
264{
265 const qint64 baseRevision = resultProvider.revision() + 1;
266 Trace() << "Running incremental query " << baseRevision;
267 return load(query, [&](Akonadi2::Storage::Transaction &transaction, QSet<QByteArray> &remainingFilters) -> ResultSet {
268 return loadIncrementalResultSet(baseRevision, query, transaction, remainingFilters);
269 }, resultProvider, false);
270}
271
272template<class DomainType>
273qint64 QueryRunner<DomainType>::executeInitialQuery(const Akonadi2::Query &query, const typename DomainType::Ptr &parent, Akonadi2::ResultProviderInterface<typename DomainType::Ptr> &resultProvider)
274{
275 auto modifiedQuery = query;
276 if (!query.parentProperty.isEmpty()) {
277 if (parent) {
278 Trace() << "Running initial query for parent:" << parent->identifier();
279 modifiedQuery.propertyFilter.insert(query.parentProperty, parent->identifier());
280 } else {
281 Trace() << "Running initial query for toplevel";
282 modifiedQuery.propertyFilter.insert(query.parentProperty, QVariant());
283 }
284 }
285 return load(modifiedQuery, [&](Akonadi2::Storage::Transaction &transaction, QSet<QByteArray> &remainingFilters) -> ResultSet {
286 return loadInitialResultSet(modifiedQuery, transaction, remainingFilters);
287 }, resultProvider, true);
288}
289
290template class QueryRunner<Akonadi2::ApplicationDomain::Folder>;
291template class QueryRunner<Akonadi2::ApplicationDomain::Mail>;
292template class QueryRunner<Akonadi2::ApplicationDomain::Event>;