File indexing completed on 2025-01-19 04:52:02
0001 /* 0002 Copyright (c) 2018 Christian Mollekopf <mollekopf@kolabsys.com> 0003 0004 This library is free software; you can redistribute it and/or modify it 0005 under the terms of the GNU Library General Public License as published by 0006 the Free Software Foundation; either version 2 of the License, or (at your 0007 option) any later version. 0008 0009 This library is distributed in the hope that it will be useful, but WITHOUT 0010 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 0011 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public 0012 License for more details. 0013 0014 You should have received a copy of the GNU Library General Public License 0015 along with this library; see the file COPYING.LIB. If not, write to the 0016 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 0017 02110-1301, USA. 0018 */ 0019 #pragma once 0020 0021 #include "kube_export.h" 0022 #include <sink/query.h> 0023 #include <sink/store.h> 0024 #include <QSharedPointer> 0025 #include <QAbstractItemModel> 0026 #include <QByteArrayList> 0027 0028 class KUBE_EXPORT EntityCacheInterface 0029 { 0030 public: 0031 typedef QSharedPointer<EntityCacheInterface> Ptr; 0032 EntityCacheInterface() = default; 0033 virtual ~EntityCacheInterface() = default; 0034 0035 virtual QVariant getProperty(const QByteArray &identifier, const QByteArray &property) const = 0; 0036 }; 0037 0038 template<typename DomainType> 0039 class KUBE_EXPORT EntityCache : public EntityCacheInterface 0040 { 0041 public: 0042 typedef QSharedPointer<EntityCache> Ptr; 0043 0044 EntityCache(const QByteArrayList &properties); 0045 virtual ~EntityCache() = default; 0046 0047 virtual QVariant getProperty(const QByteArray &, const QByteArray &) const override; 0048 0049 private: 0050 QHash<QByteArray, typename DomainType::Ptr> mCache; 0051 QSharedPointer<QAbstractItemModel> mModel; 0052 }; 0053 0054 template<typename DomainType> 0055 EntityCache<DomainType>::EntityCache(const QByteArrayList &properties) 0056 : EntityCacheInterface() 0057 { 0058 Sink::Query query; 0059 query.requestedProperties = properties; 0060 query.setFlags(Sink::Query::LiveQuery); 0061 mModel = Sink::Store::loadModel<DomainType>(query); 0062 QObject::connect(mModel.data(), &QAbstractItemModel::rowsInserted, mModel.data(), [this] (const QModelIndex &, int start, int end) { 0063 for (int row = start; row <= end; row++) { 0064 auto entity = mModel->index(row, 0, QModelIndex()).data(Sink::Store::DomainObjectRole).template value<typename DomainType::Ptr>(); 0065 mCache.insert(entity->identifier(), entity); 0066 } 0067 }); 0068 } 0069 0070 template<typename DomainType> 0071 QVariant EntityCache<DomainType>::getProperty(const QByteArray &identifier, const QByteArray &property) const 0072 { 0073 if (auto entity = mCache.value(identifier)) { 0074 return entity->getProperty(property); 0075 } 0076 return {}; 0077 } 0078