Projekt

Allgemein

Profil

« Zurück | Weiter » 

Revision 81c23b56

Von Christian Ehringfeld vor etwa 9 Jahren hinzugefügt

  • ID 81c23b56b61ddaaf7faef6f303dcfbfdd3479602
  • Nachfolger d68c7cea

init

Unterschiede anzeigen:

EntityManager.pro
#-------------------------------------------------
#
# Project created by QtCreator 2013-08-01T15:03:24
#
#-------------------------------------------------
QT += core
QT += sql
QT -= gui
TARGET = EntityManager
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
HEADERS += \
src/base/entity.h \
src/base/entitymanager.h \
src/base/enums/persistencetype.h \
src/base/database.h \
src/base/enums/databasetype.h \
src/models/artikel.h \
src/base/enums/relationtype.h \
src/base/relation.h
SOURCES += main.cpp \
src/base/entity.cpp \
src/base/entitymanager.cpp \
src/base/database.cpp \
src/models/artikel.cpp \
src/base/relation.cpp
example/models/artikel.cpp
/*
Small test class
Copyright (C) 2013 Christian Ehringfeld <c.ehringfeld@t-online.de>
This file is part of OpenTeacherTool.
OpenTeacherTool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenTeacherTool 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 General Public License
along with OpenTeacherTool. If not, see <http://www.gnu.org/licenses/>.
*/
#include "artikel.h"
namespace OpenTeacherTool {
Artikel::Artikel()
{
}
Artikel::Artikel(double preis, QString name) {
this->preis = preis;
this->name = name;
}
QHash<QString, QString> Artikel::getProperties(DatabaseType type) {
QHash<QString, QString> h = QHash<QString, QString>();
h.insert("id",this->idColumnSQL());
h.insert("preis","DOUBLE");
h.insert("name","TEXT");
return h;
}
PersistenceType Artikel::getPersistenceType() {
return OpenTeacherTool::LOCAL;
}
QHash<QString, Entity*> *Artikel::getRelations() {
return this->relations;
}
QHash<QString, QVariant> *Artikel::getAttributeValues() {
this->attributeValues->insert("id",this->id);
this->attributeValues->insert("name",this->name);
this->attributeValues->insert("preis",this->preis);
return this->attributeValues;
}
void Artikel::setAttributes(QHash<QString, QVariant> h) {
this->id = h.value("id").toInt();
this->name = h.value("name").toString();
this->preis = h.value("preis").toDouble();
}
QString Artikel::getTablename() {
return "artikel";
}
void Artikel::setPreis(double preis) {
this->preis = preis;
}
void Artikel::setName(QString name) {
this->name = name;
}
Artikel::~Artikel() {
}
}
example/models/artikel.h
/*
Small test class
Copyright (C) 2013 Christian Ehringfeld <c.ehringfeld@t-online.de>
This file is part of OpenTeacherTool.
OpenTeacherTool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenTeacherTool 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 General Public License
along with OpenTeacherTool. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ARTIKEL_H
#define ARTIKEL_H
#include "src/base/entity.h"
#include <QHash>
#include <QVariant>
namespace OpenTeacherTool {
class Artikel : public Entity
{
private:
double preis;
QString name;
public:
~Artikel();
QHash<QString, QString> getProperties(DatabaseType type);
PersistenceType getPersistenceType();
QHash<QString,Entity*>* getRelations();
QHash<QString, QVariant>* getAttributeValues();
void setAttributes(QHash<QString, QVariant> h);
QString getTablename();
void setPreis(double preis);
void setName(QString name);
Artikel();
Artikel(double preis, QString name);
};
}
#endif // ARTIKEL_H
main.cpp
#include <QCoreApplication>
#include "src/base/entity.h"
#include "src/models/artikel.h"
#include "src/base/entitymanager.h"
#include <typeinfo>
#include <QDir>
#include <QDebug>
/**
* create,remove und merge funktionieren
*/
int main(int argc, char *argv[])
{
OpenTeacherTool::EntityManager *e = new OpenTeacherTool::EntityManager("QSQLITE",QDir::currentPath() + "/db.sqlite");
OpenTeacherTool::Artikel *b= new OpenTeacherTool::Artikel(30,"Peter123");
OpenTeacherTool::Entity *entity = b->getEntity();
qDebug() << "findByAttributes:" << e->findByAttributes(entity,true);
qDebug() << "create:" << e->create(entity);
qDebug() << "findAll:" << e->findAll(entity->getTablename());
entity->setAttributes(e->findByAttributes(entity,true).at(0));
qDebug() << "AttributeValues, Artikel:" << *b->getAttributeValues();
b->setName("Peter");
b->setPreis(20);
e->remove(entity);
qDebug() << "TypID:" << typeid(entity).name();
qDebug() << entity->getId();
qDebug() << "merge:" << e->merge(entity);
delete entity;
return 0;
}
src/database.cpp
/*
Database Class for managing a database connection
Copyright (C) 2013 Christian Ehringfeld <c.ehringfeld@t-online.de>
This file is part of OpenTeacherTool.
OpenTeacherTool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenTeacherTool 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 General Public License
along with OpenTeacherTool. If not, see <http://www.gnu.org/licenses/>.
*/
#include "database.h"
namespace OpenTeacherTool {
Database::Database(QSqlDatabase database) {
this->database = database;
this->init();
this->connectionName = this->database.connectionName();
}
Database::Database(QString databaseType, QString connectionName, QString databasename) {
this->database = QSqlDatabase::addDatabase(databaseType,connectionName);
this->connectionName = connectionName;
this->database.setDatabaseName(databasename);
this->init();
}
Database::Database(QString databaseType, QString connectionName, QString hostname, QString databasename, QString username, QString password, qint64 port) {
this->database = QSqlDatabase::addDatabase(databaseType,connectionName);
this->connectionName = connectionName;
this->database.setHostName(hostname);
this->database.setDatabaseName(databasename);
this->database.setUserName(username);
this->database.setPassword(password);
this->database.setPort(port);
this->init();
}
void Database::init() {
this->database.open();
this->databasetype = this->getDatabaseType();
this->supportTransactions = this->database.driver()->hasFeature(QSqlDriver::Transactions);
this->tableList = new QStringList();
this->getTableListFromDatabase();
this->createSequenceTable();
}
DatabaseType Database::getDatabaseType() {
QString d = this->database.driverName();
if(d == "qmysql") {
return OpenTeacherTool::MYSQL;
} else if(d == "qpgsql") {
return OpenTeacherTool::PGSQL;
} else {
return OpenTeacherTool::SQLITE;
}
}
void Database::getTableListFromDatabase() {
if(this->database.open()) {
QString q = "";
if(this->databasetype == OpenTeacherTool::SQLITE) {
q = this->sqliteTableList();
} else if(this->databasetype == OpenTeacherTool::MYSQL){
q = this->mysqlTableList();
} else if(this->databasetype == OpenTeacherTool::PGSQL) {
q = this->pgsqlSeqTable();
}
QSqlQuery query = QSqlQuery(this->database);
query.prepare(q);
this->select(query);
this->setTableList(query);
}
}
void Database::setTableList(QSqlQuery &q) {
while(q.next()) {
this->tableList->append(q.value(0).toString());
}
}
QString Database::sqliteTableList() {
return "SELECT tbl_name FROM sqlite_master WHERE type='table';";
}
QString Database::mysqlTableList() {
return "SHOW TABLES;";
}
QString Database::pgsqlTableList() {
return "SELECT table_name FROM information_schema.tables WHERE table_catalog = '"+this->database.databaseName()+"';";
}
Database::~Database() {
if(this->database.isOpen()) {
this->database.close();
}
QSqlDatabase::removeDatabase(this->connectionName);
delete this->tableList;
}
QString Database::getConnectionName() {
return this->connectionName;
}
void Database::setSeqTable(bool seqTable) {
this->seqTable = seqTable;
}
bool Database::isSeqTable() {
return this->seqTable;
}
QString Database::pgsqlSeqTable() {
return "CREATE TABLE IF NOT EXISTS sequence (SEQ_NAME varchar(255) NOT NULL UNIQUE , SEQ_COUNT bigint NOT NULL);";
}
QString Database::mysqlSeqTable() {
return "CREATE TABLE IF NOT EXISTS `sequence` (`SEQ_NAME` varchar(255) NOT NULL UNIQUE , `SEQ_COUNT` bigint(20) unsigned NOT NULL) CHARSET = utf8";
}
QString Database::sqliteSeqTable() {
return "CREATE TABLE IF NOT EXISTS \"sequence\" (\"SEQ_NAME\" TEXT PRIMARY KEY NOT NULL , \"SEQ_COUNT\" INTEGER NOT NULL );";
}
QChar Database::escapeChar() {
QChar c = QChar();
if(this->databasetype == OpenTeacherTool::SQLITE) {
c = '\'';
} else if(this->databasetype == OpenTeacherTool::MYSQL) {
c = '`';
}
return c;
}
bool Database::transaction(const QString &query) {
bool rc = false;
if(supportTransactions) {
this->database.transaction();
QSqlQuery sqlquery = QSqlQuery(this->database);
sqlquery.exec(query);
if(!this->database.commit()) {
this->database.rollback();
}
} else {
rc = this->exec(query);
}
return rc;
}
QSqlQuery Database::getQuery() {
return QSqlQuery(this->database);
}
QSqlQuery Database::getQuery(const QString &prepare) {
QSqlQuery q = QSqlQuery(this->database);
q.prepare(prepare);
return q;
}
bool Database::transaction(const QStringList &queries) {
bool ok = false;
if(this->supportTransactions) {
this->database.transaction();
QSqlQuery sqlquery = QSqlQuery(this->database);
for (int var = 0; var < queries.size(); ++var) {
sqlquery.exec(queries.at(var));
}
if(!this->database.commit()) {
this->database.rollback();
} else {
ok = true;
}
} else {
ok = this->exec(queries);
}
return ok;
}
bool Database::transaction(QSqlQuery &query) {
this->database.transaction();
query.exec();
if(!this->database.commit()) {
this->database.rollback();
return false;
}
return true;
}
bool Database::transaction(QList<QSqlQuery> &queries) {
this->database.transaction();
QSqlQuery q;
for (int var = 0; var < queries.size(); ++var) {
q = queries.at(var);
q.exec();
}
if(!this->database.commit()) {
this->database.rollback();
return false;
}
return true;
}
bool Database::exec(QString query) {
this->database.transaction();
QSqlQuery q = QSqlQuery(this->database);
q.exec(query);
if(!this->database.commit()) {
this->database.rollback();
return false;
}
return true;
}
bool Database::exec(QStringList queries){
QSqlQuery q = QSqlQuery(this->database);
bool ok = true;
for (int var = 0; var < queries.size() && ok; ++var) {
ok = q.exec(queries.at(var));
if(!ok) {
break;
}
}
return ok;
}
bool Database::exec(QSqlQuery query) {
return query.exec();
}
bool Database::exec(QList<QSqlQuery> queries) {
bool ok = true;
QSqlQuery q = QSqlQuery(this->database);
for (int var = 0; var < queries.size() && ok; ++var) {
q = queries.at(var);
ok = q.exec();
if(!ok) {
break;
}
}
return ok;
}
bool Database::select(QSqlQuery &query) {
query.setForwardOnly(true);
return query.exec();
}
QSqlQuery Database::select(const QString &query) {
QSqlQuery q = QSqlQuery(this->database);
q.exec(query);
return q;
}
QString Database::querySequenceCounter() {
return "INSERT INTO sequence (SEQ_NAME, SEQ_COUNT) VALUES(\'id_count\',\'0\');";
}
void Database::refreshTableList() {
this->tableList->clear();
this->getTableListFromDatabase();
}
bool Database::containsTable(QString tblname) {
return this->tableList->contains(tblname);
}
void Database::createSequenceTable() {
if(this->database.open() && this->getLastId() == -1) {
QString query = "";
QStringList l = QStringList();
if(this->databasetype == OpenTeacherTool::MYSQL) {
query = this->mysqlSeqTable();
} else if(this->databasetype == OpenTeacherTool::SQLITE) {
query = this->sqliteSeqTable();
} else if(this->databasetype == OpenTeacherTool::PGSQL) {
query = this->pgsqlSeqTable();
}
l.append(query);
l.append(this->querySequenceCounter());
if(this->transaction(l)) {
this->setSeqTable(true);
} else {
this->setSeqTable(false);
}
} else {
this->setSeqTable(true);
}
}
bool Database::updateSequenceCounter(QSqlQuery &q) {
QList<QSqlQuery> l = QList<QSqlQuery>();
l.append(QSqlQuery("UPDATE sequence SET SEQ_COUNT=(SEQ_COUNT+1);",this->database));
l.append(q);
return this->transaction(l);
}
qint64 Database::getLastId() {
qint64 id = -1;
QSqlQuery q = this->select("SELECT SEQ_COUNT FROM sequence WHERE SEQ_NAME=\'id_count\';");
if(q.next()) {
id = q.value(0).toInt();
}
return id;
}
QSqlDatabase Database::getDatabase() {
return this->database;
}
}
src/database.h
/*
Header File Database
Copyright (C) 2013 Christian Ehringfeld <c.ehringfeld@t-online.de>
This file is part of OpenTeacherTool.
OpenTeacherTool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenTeacherTool 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 General Public License
along with OpenTeacherTool. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DATABASE_H
#define DATABASE_H
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
#include <QDebug>
#include <QtSql/QSqlError>
#include <QStringList>
#include <QList>
#include <QString>
#include <QDebug>
#include "enums/databasetype.h"
namespace OpenTeacherTool {
class Database
{
private:
QSqlDatabase database;
QString connectionName;
bool seqTable;
DatabaseType databasetype;
bool supportTransactions;
void setSeqTable(bool seqTable);
void init();
void createSequenceTable();
QString querySequenceCounter();
QStringList *tableList;
protected:
inline QString pgsqlSeqTable();
inline QString mysqlSeqTable();
inline QString sqliteSeqTable();
inline QString sqliteTableList();
inline QString mysqlTableList();
inline QString pgsqlTableList();
public:
Database(QSqlDatabase database);
~Database();
Database(QString databaseType, QString databasename);
Database(QString databaseType, QString connectionName, QString databasename);
Database(QString databaseType, QString connectionName= "", QString hostname="",QString databasename = "" , QString username ="", QString password="", qint64 port=0);
QSqlDatabase getDatabase();
QString getConnectionName();
QSqlQuery getQuery();
QSqlQuery getQuery(const QString &prepare);
bool transaction(const QString &query);
bool transaction(const QStringList &queries);
bool transaction(QSqlQuery &query);
bool transaction(QList<QSqlQuery> &queries);
bool exec(QString query);
bool exec(QStringList queries);
bool exec(QSqlQuery query);
bool exec(QList<QSqlQuery> queries);
bool select(QSqlQuery &query);
QSqlQuery select(const QString &query);
bool isSeqTable();
qint64 getLastId();
void getTableListFromDatabase();
void setTableList(QSqlQuery &q);
void refreshTableList();
bool containsTable(QString tblname);
bool updateSequenceCounter(QSqlQuery &q);
DatabaseType getDatabaseType();
QChar escapeChar();
};
}
#endif // DATABASE_H
src/entity.cpp
/*
Base class for all models
Copyright (C) 2013 Christian Ehringfeld <c.ehringfeld@t-online.de>
This file is part of OpenTeacherTool.
OpenTeacherTool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenTeacherTool 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 General Public License
along with OpenTeacherTool. If not, see <http://www.gnu.org/licenses/>.
*/
#include "entity.h"
namespace OpenTeacherTool {
Entity::Entity() {
this->id = -1;
this->relations = new QHash<QString,Entity*>();
this->attributeValues = new QHash<QString, QVariant>();
}
qint64 Entity::getId() {
return this->id;
}
void Entity::setId(qint64 id) {
this->id = id;
}
Entity::~Entity() {
delete this->relations;
delete this->attributeValues;
}
Entity* Entity::getEntity() {
return this;
}
QString Entity::idColumnSQL() {
return "id BIGINT NOT NULL";
}
//QHash<QString, QString> OpenTeacherTool::Entity::getProperties(Datebasetype t) {
// QMap<QString, QString> map = QMap<QString, QString>();
// map.insert("id",this->idColumnSQL());
// return map;
//}
//OpenTeacherTool::PersistenceType OpenTeacherTool::Entity::getPersistenceType() {
// OpenTeacherTool::PersistenceType type = SQLITE;
// return type;
//}
//QMap<QString, OpenTeacherTool::Entity> OpenTeacherTool::Entity::getRelations() {
// QMap<QString, Entity> map;
// return map;
//}
}
src/entity.h
/*
Header File Entity
Copyright (C) 2013 Christian Ehringfeld <c.ehringfeld@t-online.de>
This file is part of OpenTeacherTool.
OpenTeacherTool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenTeacherTool 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 General Public License
along with OpenTeacherTool. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MODEL_H
#define MODEL_H
#include <QtGlobal>
#include <QMap>
#include <QDebug>
#include "enums/persistencetype.h"
#include "enums/databasetype.h"
namespace OpenTeacherTool {
class Entity
{
public:
qint64 getId();
void setId(qint64 id);
Entity* getEntity();
void addAttributeVal(const QString name, QVariant *var);
virtual ~Entity();
virtual QHash<QString, QString> getProperties(DatabaseType type) = 0;
virtual PersistenceType getPersistenceType() = 0;
virtual QHash<QString,Entity*>* getRelations() = 0;
virtual QHash<QString, QVariant>* getAttributeValues() = 0;
virtual void setAttributes(QHash<QString, QVariant>) = 0;
virtual QString getTablename() = 0;
virtual QString idColumnSQL();
// virtual QMap<QString, QString> getManyToManyRelations() = 0; //Key = Table, Value = joined Table Column
protected:
Entity();
qint64 id;
QHash<QString,QVariant> *attributeValues;
QHash<QString,Entity*> *relations;
};
}
#endif // MODEL_H
src/entitymanager.cpp
/*
Entity Manager for crud operations of entities
Copyright (C) 2013 Christian Ehringfeld <c.ehringfeld@t-online.de>
This file is part of OpenTeacherTool.
OpenTeacherTool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenTeacherTool 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 General Public License
along with OpenTeacherTool. If not, see <http://www.gnu.org/licenses/>.
*/
#include "entitymanager.h"
/**
* Relationen fehlen noch
* Fehlermeldungen erstellen am besten eine Exception Klasse diesbzgl. erstellen
*/
namespace OpenTeacherTool {
QStringList EntityManager::connectionNames = QStringList();
EntityManager::EntityManager(QSqlDatabase database) {
this->db = new Database(database);
}
EntityManager::EntityManager(const QString &databaseType,QString databasename , QString hostname,QString username, QString password, QString port) {
this->db = new Database(databaseType,this->createConnection(),hostname,databasename,username,password,port.toInt());
}
inline bool EntityManager::checkTable(Entity *entity) {
bool rc = true;
if(!this->db->containsTable(entity->getTablename())) {
qDebug() << "Tabelle" << entity->getTablename() << "existiert noch nicht.";
if(this->createTable(entity)) {
this->db->refreshTableList();
rc = this->db->containsTable(entity->getTablename());
}
}
return rc;
}
QString EntityManager::createConnection() {
QStringList l = EntityManager::getConnectionNames();
QString conName = "";
bool ok = false;
qint16 i = 0;
while(!ok) {
if(l.contains("con"+QString::number(i))) {
++i;
} else {
l.append("con"+QString::number(i));
ok = true;
conName = "con"+QString::number(i);
EntityManager::setConnectionNames(l);
}
}
return conName;
}
void EntityManager::removeConnectionName(const QString &name) {
EntityManager::connectionNames.removeOne(name);
}
EntityManager::~EntityManager() {
EntityManager::removeConnectionName(this->db->getConnectionName());
delete db;
}
QStringList EntityManager::getConnectionNames() {
return EntityManager::connectionNames;
}
void EntityManager::setConnectionNames(QStringList list) {
EntityManager::connectionNames = list;
}
void EntityManager::bindValues(const QHash<QString, QVariant> *h, QSqlQuery &q, bool ignoreID) {
QHash<QString, QVariant>::const_iterator i = h->constBegin();
while(i != h->constEnd()) {
if(!ignoreID || (ignoreID && !(i.key() == "id"))) {
q.bindValue(":"+i.key(),i.value());
}
++i;
}
}
qint8 EntityManager::count(Entity* entity, bool ignoreID) {
qint8 rc = 0;
QSqlQuery q = this->db->getQuery("SELECT COUNT(*) FROM " + entity->getTablename() + this->where(entity->getAttributeValues(),"AND",ignoreID));
this->bindValues(entity->getAttributeValues(),q);
this->db->select(q);
if(q.next()) {
rc = q.value(0).toInt();
}
return rc;
}
QString EntityManager::buildCreateQuery(QHash<QString,QVariant>::const_iterator i, QHash<QString,QVariant>::const_iterator end, QString &p1, QString &p2) {
bool first = true;
while(i != end) {
if(!first) {
p1 += ",";
p2 += ",";
} else {
first = false;
}
p1 += i.key();
p2 += ":"+i.key();
++i;
}
p1 += ")";
p2 += ");";
return p1 + p2;
}
bool EntityManager::create(Entity *entity) {
bool rc = false;
if(this->checkTable(entity) && this->count(entity) == 0) {
QSqlQuery q = this->db->getQuery();
QString p1 = "INSERT INTO " + entity->getTablename() + "(";
QString p2 = "VALUES(";
entity->setId(this->db->getLastId());
if(!entity->getAttributeValues()->isEmpty()) {
q.prepare(this->buildCreateQuery(entity->getAttributeValues()->constBegin(),entity->getAttributeValues()->constEnd(),p1,p2));
}
this->bindValues(entity->getAttributeValues(),q);
if(this->db->updateSequenceCounter(q)) {
entity->setId(this->findId(entity));
rc = true;
}
}
return rc;
}
QHash<QString,QVariant> EntityManager::find(qint64 id, QString tblname) {
QSqlQuery q = this->db->getQuery("SELECT * FROM " + tblname +" WHERE id= :id LIMIT 1;");
q.bindValue(":id",id);
this->db->select(q);
QSqlRecord rec = q.record();
QHash<QString,QVariant> map = QHash<QString, QVariant>();
if(q.next()) {
for (int var = 0; var < rec.count(); ++var) {
map.insert(rec.fieldName(var),q.value(rec.indexOf(rec.fieldName(var)))); // parameters of q.value can maybe replaced with var
}
}
return map;
}
QList<QHash <QString,QVariant> > EntityManager::findByAttributes(QHash<QString, QVariant> *m, const QString &tblname, bool ignoreID) {
QSqlQuery q = this->db->getQuery("SELECT * FROM " + tblname + this->where(m,"AND",ignoreID));
this->bindValues(m,q,true);
return this->convertQueryResult(q);
}
QList<QHash<QString, QVariant> > EntityManager::convertQueryResult(QSqlQuery &q) {
QList<QHash <QString, QVariant> > listmap = QList<QHash <QString,QVariant> >();
this->db->select(q);
QSqlRecord rec = q.record();
QStringList l = QStringList();
qint16 field_count = rec.count();
for (int var = 0; var < field_count; ++var) {
l.append(rec.fieldName(var));
}
QHash<QString,QVariant> map = QHash<QString, QVariant>();
while(q.next()) {
for (int var = 0; var < field_count; ++var) {
map.insert(l.at(var),q.value(rec.indexOf(l.at(var))));
}
listmap.append(map);
}
return listmap;
}
QList<QHash <QString,QVariant> > EntityManager::findAll(QString tblname) {
QSqlQuery q =this->db->getQuery("SELECT * FROM " + tblname + ";");
return this->convertQueryResult(q);
}
bool EntityManager::merge(Entity *entity) {
if(this->count(entity) == 0 && entity->getId() != -1) {
QSqlQuery q = this->db->getQuery("UPDATE " + entity->getTablename() + " SET " +this->attributes(entity->getAttributeValues()) + " WHERE id=:idM;");
this->bindValues(entity->getAttributeValues(),q);
q.bindValue(":idM",entity->getId());
return this->db->transaction(q);
} else {
return false;
}
}
qint64 EntityManager::findId(Entity *entity) {
qint64 r = -1;
QSqlQuery q = this->db->getQuery("SELECT id FROM " + entity->getTablename() + this->where(entity->getAttributeValues(),"AND",true) + " LIMIT 1");
this->bindValues(entity->getAttributeValues(),q);
this->db->select(q);
if(q.next()) {
r = q.value(0).toInt();
}
return r;
}
QString EntityManager::attributes(QHash<QString, QVariant> *m, QString conjunction, bool ignoreID) {
QString rc = "";
if(!m->isEmpty()) {
QHash<QString, QVariant>::const_iterator i = m->constBegin();
while(i != m->constEnd()) {
if(!ignoreID || (ignoreID && !(i.key() == "id"))) {
if(!(rc == "")) {
rc += " " + conjunction + " ";
}
rc += i.key() + "= :" +i.key();
}
++i;
}
}
return rc;
}
QString EntityManager::where(QHash<QString, QVariant> *m, QString conjunction, bool ignoreID) {
if(m->size() == 0 || (ignoreID && m->contains("id") && m->size() == 1)) {
return "";
}
return " WHERE " + this->attributes(m,conjunction,ignoreID);
}
QString EntityManager::where(Entity *entity, QString conjunction, bool ignoreID) {
return this->where(entity->getAttributeValues(),conjunction,ignoreID);
}
QList<QHash <QString,QVariant> > EntityManager::findByAttributes(Entity *entity, bool ignoreID) {
return this->findByAttributes(entity->getAttributeValues(), entity->getTablename(),ignoreID);
}
bool EntityManager::save(Entity *entity) {
if(entity->getId() > -1) {
return this->merge(entity);
} else {
return this->create(entity);
}
}
bool EntityManager::remove(Entity *&entity) {
bool rc = false;
QSqlQuery q = this->db->getQuery("DELETE FROM " + entity->getTablename() + " WHERE id= :id;");
q.bindValue(":id",entity->getId());
if(this->db->transaction(q)) {
delete entity;
entity = 0;
rc = true;
}
return rc;
}
QString EntityManager::createTableQuery(Entity *entity) {
QChar c = this->db->escapeChar();
QHash<QString, QString> m = entity->getProperties(this->db->getDatabaseType());
bool first = true;
QString s = "CREATE TABLE IF NOT EXISTS ";
s.append(c).append(entity->getTablename()).append(c).append("(");
QHash<QString, QString>::const_iterator i = m.constBegin();
while (i != m.constEnd()) {
if(first) {
first = false;
} else {
s.append(',');
}
s.append(c).append(i.key()).append(c).append(" " + i.value());
++i;
}
s.append(");");
return s;
}
bool EntityManager::createTable(Entity *entity) {
bool rc = false;
this->db->containsTable(entity->getTablename()) ? rc = true : rc = false;
if(!rc) {
QSqlQuery q = this->db->getQuery(this->createTableQuery(entity));
if(this->db->transaction(q)) {
this->db->refreshTableList();
rc = true;
}
}
return rc;
}
}
src/entitymanager.h
/*
Header File Entity Manager
Copyright (C) 2013 Christian Ehringfeld <c.ehringfeld@t-online.de>
This file is part of OpenTeacherTool.
OpenTeacherTool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenTeacherTool 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 General Public License
along with OpenTeacherTool. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ENTITYMANAGER_H
#define ENTITYMANAGER_H
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlRecord>
#include <QtSql/QSqlField>
#include <QString>
#include <QStringList>
#include <QDebug>
#include <QtSql/QSqlError>
#include "entity.h"
#include "database.h"
namespace OpenTeacherTool {
class EntityManager
{
private:
static QStringList connectionNames;
static void setConnectionNames(QStringList list);
Database *db;
QString createConnection();
QString createTableQuery(Entity *entity);
QString attributes(QHash<QString, QVariant> *m, QString conjunction=",", bool ignoreID = false);
QList<QHash<QString, QVariant> > convertQueryResult(QSqlQuery &q);
bool checkTable(Entity *entity);
QString buildCreateQuery(QHash<QString,QVariant>::const_iterator i, QHash<QString,QVariant>::const_iterator end,QString &p1, QString &p2);
void bindValues(const QHash<QString, QVariant> *h, QSqlQuery &q, bool ignoreID = false);
protected:
QString where(Entity *entity,QString conjunction=",",bool ignoreID = false);
QString where(QHash<QString, QVariant> *m,QString conjunction=",", bool ignoreID = false);
public:
EntityManager(QSqlDatabase database);
EntityManager(const QString &databaseType, QString databasename = "" , QString hostname="", QString username ="", QString password="", QString port="");
~EntityManager();
static QStringList getConnectionNames();
static void removeConnectionName(const QString &name);
bool create(Entity *entity);
bool save(Entity *entity);
qint64 findId(Entity *entity);
QList<QHash<QString,QVariant> > findAll(QString tblname);
QHash<QString,QVariant> find(qint64 id, QString tblname);
QList<QHash<QString, QVariant> > findByAttributes(Entity *entity,bool ignoreID = false);
QList<QHash<QString, QVariant> > findByAttributes(QHash<QString, QVariant> *m, const QString &tblname, bool ignoreID = false);
bool merge(Entity *entity);
bool remove(Entity *&entity);
bool removeAll(QString tblname);
bool createTable(Entity *entity);
qint8 count(Entity* entity, bool ignoreID= true);
};
}
#endif // ENTITYMANAGER_H
src/enums/databasetype.h
/*
Enum DatabaseType
Copyright (C) 2013 Christian Ehringfeld <c.ehringfeld@t-online.de>
This file is part of OpenTeacherTool.
OpenTeacherTool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenTeacherTool 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 General Public License
along with OpenTeacherTool. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DATABASETYPE_H
#define DATABASETYPE_H
namespace OpenTeacherTool {
enum DatabaseType {
SQLITE=0,
PGSQL=1,
MYSQL=2
};
}
#endif // DATABASETYPE_H
src/enums/persistencetype.h
/*
OpenTeacherTool, a platform independent tool for schoolteacher
Copyright (C) 2013 Yves Bodenheimer, Christian Ehringfeld, David Mock
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
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 General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PERSISTENCETYPE_H
#define PERSISTENCETYPE_H
#include <QObject>
#include <QMap>
#include <QString>
namespace OpenTeacherTool {
enum PersistenceType {
LOCAL=0,
XML=1,
REMOTEDATABASE=2
};
static QMap<PersistenceType, QString> initMap() {
QMap<PersistenceType, QString> map;
map[LOCAL] = QObject::tr("LocalDatabase");
map[XML] = QObject::tr("XMLFile");
map[REMOTEDATABASE] = QObject::tr("RemoteDatabase");
return map;
}
static QString toString(const PersistenceType &type) {
static QMap<PersistenceType, QString> map = initMap();
return map[type];
}
}
#endif // PERSISTENCETYPE_H
src/enums/relationtype.h
/*
OpenTeacherTool, a platform independent tool for schoolteacher
Copyright (C) 2013 Yves Bodenheimer, Christian Ehringfeld, David Mock
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
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 General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RELATIONTYPE_H
#define RELATIONTYPE_H
namespace OpenTeacherTool{
enum Relationtype {
ONETOONE=0,
ONETOMANY=1,
MANYTOONE=2,
MANYTOMANY=3
};
}
#endif // RELATIONTYPE_H
src/relation.cpp
/*
OpenTeacherTool, a platform independent tool for schoolteacher
Copyright (C) 2013 Yves Bodenheimer, Christian Ehringfeld, David Mock
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
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 General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "relation.h"
namespace OpenTeacherTool {
Relation::Relation()
{
}
}
src/relation.h
/*
OpenTeacherTool, a platform independent tool for schoolteacher
Copyright (C) 2013 Yves Bodenheimer, Christian Ehringfeld, David Mock
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
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 General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RELATION_H
#define RELATION_H
#include "entity.h"
#include "src/base/enums/relationtype.h"
namespace OpenTeacherTool {
class Relation
{
public:
Relation();
private:
Entity* foreignEntity;
OpenTeacherTool::Relationtype Relationtype;
};
}
#endif // RELATION_H

Auch abrufbar als: Unified diff