Projekt

Allgemein

Profil

Herunterladen als
Herunterladen (17,6 KB) Statistiken
| Zweig: | Revision:
81c23b56 Christian Ehringfeld
/*
6899f814 Christian Ehringfeld
* Copyright (C) 2015 Christian Ehringfeld <c.ehringfeld@t-online.de>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
81c23b56 Christian Ehringfeld
#ifndef ENTITYMANAGER_H
#define ENTITYMANAGER_H
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlRecord>
#include <QtSql/QSqlField>
#include <QString>
#include <QStringList>
ac8aede7 Christian Ehringfeld
#include <QObject>
586bb527 Christian Ehringfeld
#include <QSharedPointer>
81c23b56 Christian Ehringfeld
#include <QDebug>
#include <QtSql/QSqlError>
a205e8a9 Christian Ehringfeld
#include <QMetaType>
82442988 Christian Ehringfeld
#include "schema.h"
81c23b56 Christian Ehringfeld
#include "entity.h"
#include "database.h"
a205e8a9 Christian Ehringfeld
#include "entityinstancefactory.h"
506067a2 Christian Ehringfeld
#include "queryinterpreter.h"
82442988 Christian Ehringfeld
#include "cache.h"
#include "querybuilder.h"
fc14f551 Christian Ehringfeld
#include "validators/errormsg.h"
6899f814 Christian Ehringfeld
namespace CuteEntityManager {
f12670e9 Christian Ehringfeld
#ifdef QT_DEBUG
#define DEFAULTMSGTYPE MsgType::DEBUG
#define INSPECTENTITIES true
#else
#define DEFAULTMSGTYPE MsgType::CRITICAL
#define INSPECTENTITIES false
#endif

81c23b56 Christian Ehringfeld
45135a14 Christian Ehringfeld
class Logger;
2ee5022f Christian Ehringfeld
class QueryInterpreter;
ac8aede7 Christian Ehringfeld
class EntityManager : public QObject {
Q_OBJECT
612083d3 Christian Ehringfeld
public slots:
1708f3a8 Christian Ehringfeld
/**
* @brief startup
* @param version must be unique
* @param toInitialize list of entity classnames which database tables should be created
* @return
*/
5baea70c Christian Ehringfeld
bool startup(QString version, QStringList toInitialize,
bool createIndices = false);
e0e1ead8 Christian Ehringfeld
bool executeQuery(const QString &query);
2d9fab10 Christian Ehringfeld
QSharedPointer<Entity> findById(const qint64 &id, const QString &classname);
e0e1ead8 Christian Ehringfeld
QList<QSharedPointer<Entity>> findEntityByAttributes(const
612083d3 Christian Ehringfeld
QSharedPointer<Entity> &entity,
bool ignoreID = false);
0d155b40 Christian Ehringfeld
qint64 findId(QSharedPointer<Entity> &entity);
d2bebf1b Christian Ehringfeld
/**
* @todo should be an insert statement with many values
e5a0d313 Christian Ehringfeld
* @todo error handling
d2bebf1b Christian Ehringfeld
* @brief EntityManager::create
* @param entities
* @return
*/
e5a0d313 Christian Ehringfeld
bool create(QList<QSharedPointer<Entity>> &entities, const bool persistRelations = true,
const bool checkDuplicate = false, const bool validate = true,
const bool relationsIgnoreHasChanged = false);
3938a37e Christian Ehringfeld
/**
* @brief EntityManager::create
* Will persist an entity in the database. Before its persisted it has the id -1(invalid id). If database persisting was succesfull it has a valid id.
* @param entity
* @param persistRelations
* @param checkDuplicate
* @param validate
* @return
*/
696666eb Christian Ehringfeld
bool create(QSharedPointer<Entity> &entity, const bool persistRelations = true,
e332a521 Christian Ehringfeld
const bool checkDuplicate = false, const bool validate = true,
const bool relationsIgnoreHasChanged = false) ;
3938a37e Christian Ehringfeld
/**
* @brief EntityManager::save
* If the entity has no valid ID, this method will call the create() method. Else it would call the merge method.
* @param entity
* @param persistRelations
* @param ignoreHasChanged
* @param validate
* @return bool
*/
28d2f01a Christian Ehringfeld
bool save(QSharedPointer<Entity> &entity, const bool persistRelations = true,
e332a521 Christian Ehringfeld
const bool ignoreHasChanged = false, const bool validate = true,
const bool relationsIgnoreHasChanged = false);
87739ae0 Christian Ehringfeld
bool save(QList<QSharedPointer<Entity>> &entities,
const bool persistRelations = true,
const bool ignoreHasChanged = false, const bool validate = true,
const bool relationsIgnoreHasChanged = false);
fc14f551 Christian Ehringfeld
bool merge(QSharedPointer<Entity> &entity, bool withRelations = true,
d2bebf1b Christian Ehringfeld
const bool validate = true, const bool relationsIgnoreHasChanged = false);
9070a496 Christian Ehringfeld
bool remove(QSharedPointer<Entity> &entity);
bool removeAll(QString tblname);
df1e56bd Christian Ehringfeld
bool createTable(const QSharedPointer<Entity> &entity,
bool createRelationTables = true);
0ec1cbfb Christian Ehringfeld
bool createTable(QString className, bool createRelationTables = true);
87739ae0 Christian Ehringfeld
quint8 count(const QSharedPointer<Entity> &entity, bool ignoreID = true,
bool followInheritance = false);
506067a2 Christian Ehringfeld
quint8 count(const QString &tableName);
9070a496 Christian Ehringfeld
QSharedPointer<Database> getDb() const;
void setDb(const QSharedPointer<Database> &value);
QSharedPointer<Schema> getSchema() const;
6d46f506 Christian Ehringfeld
/**
* @brief EntityManager::refresh
* fetches an entity again from the database
* @param entity
*/
4f3b13f3 Christian Ehringfeld
void refresh(QSharedPointer<Entity> &entity);
6be60ddf Christian Ehringfeld
QList<QHash<QString, QVariant>> selectByQuery(Query &query);
QList<QHash<QString, QVariant>> selectBySql(const QString &sql);
506067a2 Christian Ehringfeld
qint8 count(Query &query);
d2bebf1b Christian Ehringfeld
/**
* @brief EntityManager::validate
* This validates an entity. Its uses the validationRules() method of the specified entity.
* If there are validation errors, this method will set these errors in the entity object.
* You can check them with entity->hasErrors(), entity->getErrors() or entity->getErrorsAsString()
* @param entity
* @return true if it has no validation errors, false if it has errors
*/
fc14f551 Christian Ehringfeld
bool validate(QSharedPointer<Entity> &entity);
d2bebf1b Christian Ehringfeld
/**
* @brief hasChanged
* @param entity
* @todo check manyToMany relations
* @return
*/
554f7bc0 Christian Ehringfeld
bool hasChanged(QSharedPointer<Entity> &entity);

612083d3 Christian Ehringfeld
public:
f12670e9 Christian Ehringfeld
EntityManager(QSqlDatabase database, bool logQueries = false,
const bool inspectEntities = INSPECTENTITIES,
MsgType logActions = DEFAULTMSGTYPE);
dc618bda Christian Ehringfeld
EntityManager(const QString &databaseType, QString databasename = "" ,
QString hostname = "",
QString username = "",
5baea70c Christian Ehringfeld
QString password = "", QString port = "", bool logQueries = false,
f12670e9 Christian Ehringfeld
QString databaseOptions = "", const bool inspectEntities = INSPECTENTITIES,
MsgType logActions = DEFAULTMSGTYPE);
28d2f01a Christian Ehringfeld
virtual ~EntityManager();
dc618bda Christian Ehringfeld
static QStringList getConnectionNames();
28d2f01a Christian Ehringfeld
static void removeConnectionName(const QString &name);
static QHash<QString, EntityManager *> getInstances();
static EntityManager *getDefaultInstance();
static EntityManager *getInstance(QString name);
dc618bda Christian Ehringfeld
QSharedPointer<QueryBuilder> getQueryBuilder() const;
1b167b6c Christian Ehringfeld
c9f21778 Christian Ehringfeld
template<class T> QList<QSharedPointer<T>> find(Query &q,
612083d3 Christian Ehringfeld
const bool joinBaseClasses = false, const bool resolveRelations = true) {
1b167b6c Christian Ehringfeld
QSharedPointer<Entity> ptr = QSharedPointer<Entity>
612083d3 Christian Ehringfeld
(EntityInstanceFactory::createInstance<T *>());
1b167b6c Christian Ehringfeld
if (ptr) {
if (q.getFrom().isEmpty()) {
q.setFrom(QStringList(ptr->getTablename()));
}
c9f21778 Christian Ehringfeld
if (joinBaseClasses) {
q.appendJoins(this->schema->getQueryBuilder()->joinBaseClasses(ptr));
}
1b167b6c Christian Ehringfeld
QSqlQuery query = this->queryInterpreter->build(q);
auto maps = this->convertQueryResult(query);
c9f21778 Christian Ehringfeld
auto converted = this->convert(maps, EntityHelper::getClassname(ptr.data()),
5baea70c Christian Ehringfeld
false,
c9f21778 Christian Ehringfeld
resolveRelations);
6be60ddf Christian Ehringfeld
return EntityManager::convertList<T>(converted);
1b167b6c Christian Ehringfeld
}
return QList<QSharedPointer<T>>();
}

c9f21778 Christian Ehringfeld
template<class T> QList<QSharedPointer<T>> findAll(const bool resolveRelations =
612083d3 Christian Ehringfeld
true) {
6d91d381 Christian Ehringfeld
QSharedPointer<Entity> ptr = QSharedPointer<Entity>
612083d3 Christian Ehringfeld
(EntityInstanceFactory::createInstance<T *>());
6d91d381 Christian Ehringfeld
if (ptr) {
f5087482 Christian Ehringfeld
auto maps = this->findAll(ptr);
c9f21778 Christian Ehringfeld
auto converted = this->convert(maps, EntityHelper::getClassname(ptr.data()),
44fed106 Christian Ehringfeld
false,
c9f21778 Christian Ehringfeld
resolveRelations);
6be60ddf Christian Ehringfeld
return EntityManager::convertList<T>(converted);
9070a496 Christian Ehringfeld
}
506067a2 Christian Ehringfeld
return QList<QSharedPointer<T>>();
9070a496 Christian Ehringfeld
}

506067a2 Christian Ehringfeld
template<class T> QSharedPointer<T> findById(const qint64 &id) {
auto e = EntityInstanceFactory::createInstance<T *>();
f5087482 Christian Ehringfeld
QSharedPointer<Entity> ptr = QSharedPointer<Entity>(e);
506067a2 Christian Ehringfeld
return this->findById(id, ptr).objectCast<T>();
a205e8a9 Christian Ehringfeld
}
9070a496 Christian Ehringfeld
c9f21778 Christian Ehringfeld
template<class T>
QSharedPointer<T> findEntityByAttributes(
612083d3 Christian Ehringfeld
const QHash<QString, QVariant>
&attributes, const bool joinBaseClasses = false,
const bool resolveRelations = true) {
c9f21778 Christian Ehringfeld
auto list = this->findAllEntitiesByAttributes<T>(attributes, 1, 0,
612083d3 Christian Ehringfeld
joinBaseClasses, resolveRelations);
11bbe9a6 Christian Ehringfeld
if (list.isEmpty()) {
506067a2 Christian Ehringfeld
return QSharedPointer<T>();
11bbe9a6 Christian Ehringfeld
}
506067a2 Christian Ehringfeld
QSharedPointer<Entity> obj = list.at(0);
return obj.objectCast<T>();
d84c91e7 Christian Ehringfeld
}

506067a2 Christian Ehringfeld
template<class T> QList<QSharedPointer<T>> findAllEntitiesByAttributes(
const QHash<QString, QVariant> &attributes =
6be60ddf Christian Ehringfeld
QHash<QString, QVariant>(), quint64 limit = 0, quint64 offset = 0,
612083d3 Christian Ehringfeld
bool joinBaseClasses = false, const bool resolveRelations = true) {
9e44a59b Christian Ehringfeld
QSharedPointer<Entity> e = QSharedPointer<Entity>
dbf92b46 Christian Ehringfeld
(EntityInstanceFactory::createInstance<T*>());
ac5cbdcf Christian Ehringfeld
if (e) {
9e44a59b Christian Ehringfeld
Query query = Query(QStringList(e->getTablename()));
c9f21778 Christian Ehringfeld
if (joinBaseClasses) {
query.appendJoins(this->schema->getQueryBuilder()->joinBaseClasses(e));
}
9e44a59b Christian Ehringfeld
query.appendWhere(this->schema->getQueryBuilder()->where(attributes));
506067a2 Christian Ehringfeld
query.setLimit(limit);
query.setOffset(offset);
QSqlQuery q = this->queryInterpreter->build(query);
auto results = this->convertQueryResult(q);
44fed106 Christian Ehringfeld
auto list = this->convert(results, EntityHelper::getClassname(e.data()), false,
c9f21778 Christian Ehringfeld
resolveRelations);
6be60ddf Christian Ehringfeld
return EntityManager::convertList<T>(list);
ac5cbdcf Christian Ehringfeld
}
9e44a59b Christian Ehringfeld
return QList<QSharedPointer<T>>();
11bbe9a6 Christian Ehringfeld
}
d84c91e7 Christian Ehringfeld
506067a2 Christian Ehringfeld
template<class T> QList<QSharedPointer<T>> findEntitiesBySql(
612083d3 Christian Ehringfeld
const QString &sql) {
506067a2 Christian Ehringfeld
QSharedPointer<T> e = EntityInstanceFactory::createInstance<T *>();
11bbe9a6 Christian Ehringfeld
if (e) {
dc618bda Christian Ehringfeld
QSqlQuery q = this->schema->getDatabase()->getQuery(sql);
11bbe9a6 Christian Ehringfeld
auto result = this->convertQueryResult(q);
506067a2 Christian Ehringfeld
auto converted = this->convert(result, EntityHelper::getClassname(e));
6be60ddf Christian Ehringfeld
return EntityManager::convertList<T>(converted);
11bbe9a6 Christian Ehringfeld
}
506067a2 Christian Ehringfeld
return QList<QSharedPointer<T>>();
d84c91e7 Christian Ehringfeld
}
dc6b13b4 Christian Ehringfeld
11bbe9a6 Christian Ehringfeld
template<class T> bool remove(const QList<qint64> &ids) {
bool ok = true;
foreach (qint64 var, ids) {
506067a2 Christian Ehringfeld
if (!this->remove<T *>(var)) {
11bbe9a6 Christian Ehringfeld
ok = false;
break;
}
}
return ok;
}
d84c91e7 Christian Ehringfeld
11bbe9a6 Christian Ehringfeld
template<class T> bool remove(qint64 id) {
506067a2 Christian Ehringfeld
Entity *e = EntityInstanceFactory::createInstance<T *>();
9070a496 Christian Ehringfeld
if (e) {
QSharedPointer<Entity> ptr = QSharedPointer<Entity>(e);
abb9e8c5 Christian Ehringfeld
ptr->setId(id);
9070a496 Christian Ehringfeld
return this->remove(ptr);
}
return false;
d84c91e7 Christian Ehringfeld
}
11bbe9a6 Christian Ehringfeld
612083d3 Christian Ehringfeld
template<class T, class X>
6be60ddf Christian Ehringfeld
static QList<QSharedPointer<T>> convertList(const QList<QSharedPointer<X>> &list) {
139a9b5e Christian Ehringfeld
QList<QSharedPointer<T>> newList = QList<QSharedPointer<T>>();
for (int i = 0; i < list.size(); ++i) {
612083d3 Christian Ehringfeld
newList.append(qSharedPointerObjectCast<T>(list.at(i)));
139a9b5e Christian Ehringfeld
}
return newList;
}

612083d3 Christian Ehringfeld
protected:
d2bebf1b Christian Ehringfeld
bool saveObject(QSharedPointer<Entity> &entity, QList<Entity *> &mergedObjects,
const bool persistRelations = true,
const bool ignoreHasChanged = false, const bool validate = true,
const bool relationsIgnoreHasChanged = false);
bool mergeObject(QSharedPointer<Entity> &entity, QList<Entity *> &mergedObjects,
bool withRelations,
const bool validate, const bool relationsIgnoreHasChanged = false);
bool createObject(QSharedPointer<Entity> &entity,
QList<Entity *> &mergedObjects, const bool persistRelations,
const bool checkDuplicate, const bool validate,
const bool relationsIgnoreHasChanged = false);
f12670e9 Christian Ehringfeld
void init(bool inspect, const MsgType msgType);
6be60ddf Christian Ehringfeld
QList<QHash<QString, QVariant>> findAll(const QSharedPointer<Entity> &e);
a82e4cea Christian Ehringfeld
void resolveRelations(const QSharedPointer<Entity> &entity,
const QHash<QString, QVariant> &map, const bool refresh = false);
QHash<QString, QVariant> findByPk(qint64 id, const QSharedPointer<Entity> &e);
void manyToOne(const QSharedPointer<Entity> &entity, const QVariant &id,
const QMetaProperty &property, const bool refresh = false);
void oneToMany(const QSharedPointer<Entity> &entity, const Relation &r,
const QMetaProperty &property, const bool refresh = false);
void manyToMany(const QSharedPointer<Entity> &entity,
66704054 Christian Ehringfeld
const QMetaProperty &property, const Relation &relation,
const bool refresh = false);
a82e4cea Christian Ehringfeld
void oneToOne(const QSharedPointer<Entity> &entity, const Relation &r,
const QMetaProperty &property, const bool refresh = false,
const QVariant &id = "");
void persistManyToMany(const QSharedPointer<Entity> &entity, const Relation &r,
d2bebf1b Christian Ehringfeld
QVariant &property, QList<Entity *> &mergedObjects,
87739ae0 Christian Ehringfeld
const bool ignoreHasChanged = false, const bool newItem = false);
6be60ddf Christian Ehringfeld
QList<QHash<QString, QVariant>> findAllByAttributes(const
QSharedPointer<Entity> &entity,
bool ignoreID = false);
QList<QHash<QString, QVariant>> findAllByAttributes(const
QHash<QString, QVariant> &m,
const QString &tblname,
bool ignoreID = false);
a82e4cea Christian Ehringfeld
QSharedPointer<Entity> findById(const qint64 &id, QSharedPointer<Entity> &e,
const bool refresh = false);
d2bebf1b Christian Ehringfeld
/**
* @brief EntityManager::savePrePersistedRelations
* @param entity
* @param mergedObjects
* @throw can throw in debug mode a QString exception when the type of any Relation is wrong @see EntityManager::checkRelation
*/
void savePrePersistedRelations(const QSharedPointer<Entity> &entity,
QList<Entity *> &mergedObjects, bool ignoreHasChanged = false);
/**
* @brief EntityManager::savePostPersistedRelations
* @param entity
* @param mergedObjects
* @throw can throw in debug mode a QString exception when the type of any Relation is wrong @see EntityManager::checkRelation
*/
void savePostPersistedRelations(const QSharedPointer<Entity> &entity,
87739ae0 Christian Ehringfeld
QList<Entity *> &mergedObjects, bool ignoreHasChanged = false,
bool newItem = false);
a82e4cea Christian Ehringfeld
QList<QSharedPointer<Entity>> saveRelationEntities(const
612083d3 Christian Ehringfeld
QList<QSharedPointer<Entity>> &list, const Relation &r,
QList<Entity *> &mergedObjects);
d2bebf1b Christian Ehringfeld
/**
* @brief EntityManager::persistManyToMany
* @param entity
* @param r
* @param property
* @param mergedObjects
* @todo compare old values with new values if nothing has changed don't persist them
*/
a82e4cea Christian Ehringfeld
void persistMappedByRelation(const QList<QSharedPointer<Entity>> &list,
QSqlQuery &q, const QSharedPointer<Entity> &entity,
const QSharedPointer<Entity> &ptr, const Relation &r,
d2bebf1b Christian Ehringfeld
const QString &tblName, QList<Entity *> &mergedObjects);
a82e4cea Christian Ehringfeld
bool shouldBeSaved(QSharedPointer<Entity> &entity , const Relation &r);
void removeRelations(const QSharedPointer<Entity> &entity);
void removeEntityList(QVariant &var);
void removeManyToManyEntityList(const QSharedPointer<Entity> &e,
const Relation &r, QVariant &var);
void removeEntity(QVariant &var);
void setNullOneToManyRelation(QVariant &var, const Relation &r);
void setNullEntityPropertyRelation(QVariant &var, const Relation &r);
e8d1537c Christian Ehringfeld
QSharedPointer<Entity> convert(const QHash<QString, QVariant> &map,
c9f21778 Christian Ehringfeld
const char *classname, const bool refresh = false,
const bool resolveRelations = true);
6be60ddf Christian Ehringfeld
QList<QSharedPointer<Entity>> convert(QList<QHash<QString, QVariant>> maps,
c9f21778 Christian Ehringfeld
const char *classname, const bool refresh = false,
const bool resolveRelations = true);
66704054 Christian Ehringfeld
void missingManyToManyTable(const QString &tblName,
const QSharedPointer<Entity> &e, const Relation &r);
d2bebf1b Christian Ehringfeld
/**
* @brief EntityManager::generateObjectName
* Generates a object name with this scheme: em[anyNumber]
* @return
*/
28d2f01a Christian Ehringfeld
QString generateObjectName();
void appendToInstanceList();
a82e4cea Christian Ehringfeld
612083d3 Christian Ehringfeld
private:
a82e4cea Christian Ehringfeld
static QStringList connectionNames;
28d2f01a Christian Ehringfeld
static QHash<QString, EntityManager *> instances;
3938a37e Christian Ehringfeld
QSharedPointer<Logger> logger;
28d2f01a Christian Ehringfeld
QString id;
a82e4cea Christian Ehringfeld
QSharedPointer<Schema> schema;
static void setConnectionNames(QStringList list);
QSharedPointer<Database> db;
Cache cache;
QString createConnection();
6be60ddf Christian Ehringfeld
QList<QHash<QString, QVariant>> convertQueryResult(QSqlQuery &q);
6d46f506 Christian Ehringfeld
/**
* @brief EntityManager::checkTable
* Checks if a table has been already created, if not it will create it
* @param entity
* @return
*/
a82e4cea Christian Ehringfeld
bool checkTable(const QSharedPointer<Entity> &entity);
2ee5022f Christian Ehringfeld
QSharedPointer<QueryInterpreter> queryInterpreter;
a82e4cea Christian Ehringfeld
81c23b56 Christian Ehringfeld
};
}
abb9e8c5 Christian Ehringfeld
Q_DECLARE_METATYPE(QSharedPointer<CuteEntityManager::Entity>)
81c23b56 Christian Ehringfeld
#endif // ENTITYMANAGER_H