Projekt

Allgemein

Profil

« Zurück | Weiter » 

Revision abb9e8c5

Von Christian Ehringfeld vor mehr als 9 Jahren hinzugefügt

  • ID abb9e8c5d716850adf461b0742da96c6e4030526
  • Vorgänger f6a3fe0a
  • Nachfolger 3fd96253

example not working - wip, maybe tomorrow

Unterschiede anzeigen:

samples/example/main.cpp
#include "models/contact.h"
#include "models/group.h"
#include "models/faker/createfakemodeldata.h"
#include <typeinfo>
/**
* create,remove und merge funktionieren
*/
samples/example/models/faker/createfakemodeldata.cpp
#include "../group.h"
void CreateFakeModelData::fillGroup(Group* group) {
group->addPerson(new Person("Tim","Berg",MALE,"Tim Berg.jpg",QString(),QString(),QDate(2000,7,13),0));
group->addPerson(new Person("Lena","Conrad",FEMALE,"Lena Conrad.jpg",QString(),QString(),QDate(2000,7,13),0));
group->addPerson(new Person("Marcel","Dunst",MALE,"Marcel Dunst.jpg",QString(),QString(),QDate(2000,7,13),0));
group->addPerson(new Person("Carsten","Ernst",MALE,"Carsten Ernst.jpg",QString(),QString(),QDate(2000,7,13),0));
group->addPerson(new Person("Hannah","Eschborn",FEMALE,"Hannah Eschborn.jpg",QString(),QString(),QDate(2000,7,13),0));
group->addPerson(new Person("Vera","Geseke",FEMALE,"Vera Geseke.jpg",QString(),QString(),QDate(2000,4,1),0));
group->addPerson(new Person("Jann","Hagedorn",MALE,"Jann Hagedorn.jpg",QString(),QString(),QDate(2000,8,16),0));
group->addPerson(new Person("Svenja","Hartmann",FEMALE,"Svenja Hartmann.jpg",QString(),QString(),QDate(2000,2,2),0));
group->addPerson(new Person("Timo","Haufer",MALE,"Timo Haufer.jpg",QString(),QString(),QDate(2000,2,28),0));
group->addPupil(new Pupil("Tim","Berg",MALE,"Tim Berg.jpg",QString(),QString(),QDate(2000,7,13),"05c",0));
group->addPupil(new Pupil("Lena","Conrad",FEMALE,"Lena Conrad.jpg",QString(),QString(),QDate(2000,7,13),"05c",0));
group->addPupil(new Pupil("Marcel","Dunst",MALE,"Marcel Dunst.jpg",QString(),QString(),QDate(2000,7,13),"05c",0));
samples/example/models/group.cpp
const QHash<QString, CuteEntityManager::Relation> Group::getRelations() const {
auto hash = QHash<QString, CuteEntityManager::Relation>();
hash.insert("pupils", CuteEntityManager::Relation("pupils", MANY_TO_MANY));
//hash.insert("pupils", CuteEntityManager::Relation("pupils", MANY_TO_MANY));
hash.insert("persons", CuteEntityManager::Relation("persons", MANY_TO_MANY));
hash.insert("mainTeacher", CuteEntityManager::Relation("mainTeacher",
MANY_TO_ONE));
return hash;
......
void Group::setMainTeacher(const QSharedPointer<Person> &value) {
mainTeacher = value;
}
QList<QSharedPointer<Person> > Group::getPersons() const {
return persons;
}
void Group::addPerson(Person *person) {
this->persons.append(QSharedPointer<Person>(person));
}
void Group::setPersons(const QList<QSharedPointer<Person> > &value) {
persons = value;
}
samples/example/models/group.h
class Group: public CuteEntityManager::Entity {
Q_OBJECT
Q_PROPERTY(QList<QSharedPointer<Pupil>> pupils READ getPupils WRITE setPupils)
//Q_PROPERTY(QList<QSharedPointer<Pupil>> pupils READ getPupils WRITE setPupils)
Q_PROPERTY(QList<QSharedPointer<Person>> persons READ getPersons WRITE setPersons)
Q_PROPERTY(QString name READ getName WRITE setName)
Q_PROPERTY(QSharedPointer<Person> mainTeacher READ getMainTeacher WRITE
setMainTeacher)
......
QSharedPointer<Person> getMainTeacher() const;
void setMainTeacher(const QSharedPointer<Person> &value);
protected:
QList<QSharedPointer<Person> > getPersons() const;
void addPerson(Person *person);
void setPersons(const QList<QSharedPointer<Person> > &value);
protected:
QList<QSharedPointer<Pupil>> pupils;
QList<QSharedPointer<Person>> persons;
QSharedPointer<Person> mainTeacher;
QString name;
};
samples/example/models/person.h
public:
Q_INVOKABLE explicit Person(QObject *parent = 0);
Person(QString firstName,
QString familyName,
Gender gender = UNKNOWNGENDER,
QString customPictureFileName = QString(),
QString namePrefix = QString(),
QString nickName = QString(),
QDate birthday = QDate(),
QObject *parent = 0);
Person(QString firstName, QString familyName, Gender gender = UNKNOWNGENDER,
QString customPictureFileName = QString(), QString namePrefix = QString(),
QString nickName = QString(), QDate birthday = QDate(), QObject *parent = 0);
virtual const QHash<QString, CuteEntityManager::Relation> getRelations() const;
......
Gender gender;
QString customPictureFileName;
QList <QSharedPointer<Contact>> contacts;
QList <QSharedPointer<Address>>addresses;
QList<QSharedPointer<Group>> groups;
QList <QSharedPointer<Address>> addresses;
QList <QSharedPointer<Group>> groups;
};
samples/example/models/pupil.cpp
void Pupil::setForm(const QString &value) {
form = value;
}
QString Pupil::getLegalGuardianNote() const
{
return legalGuardianNote;
}
void Pupil::setLegalGuardianNote(const QString &value)
{
legalGuardianNote = value;
}
samples/example/models/pupil.h
class Pupil : public Person {
Q_OBJECT
Q_PROPERTY(QString legalGuardianNote READ getLegalGuardianNote WRITE
setLegalGuardianNote)
public:
Q_INVOKABLE Pupil();
Pupil(QString firstName, QString familyName, Gender gender = UNKNOWNGENDER,
......
QString getForm() const;
void setForm(const QString &value);
QString getLegalGuardianNote() const;
void setLegalGuardianNote(const QString &value);
protected:
QString form;
QString legalGuardianNote;
};
src/cache.cpp
}
void Cache::insert(QSharedPointer<Entity> &entity) {
if (entity.data() && entity.data()->getId() > -1) {
QString key = this->generateKey(entity.data()->getId(),
QString(entity.data()->getClassname()));
if (entity.data() && entity->getId() > -1) {
QString key = this->generateKey(entity->getId(),
QString(entity->getClassname()));
if (this->cache.contains(key)) {
QSharedPointer<Entity> ptr = this->cache.value(key).toStrongRef();
if (!ptr.isNull()) {
......
}
void Cache::remove(const QSharedPointer<Entity> &entity) {
if (entity.data() && entity.data()->getId() > -1) {
this->remove(entity.data()->getId(), QString(entity.data()->getClassname()));
if (entity.data() && entity->getId() > -1) {
this->remove(entity->getId(), QString(entity->getClassname()));
}
}
src/entity.cpp
}
QVariant Entity::property(const QString &name) const {
return this->property(name.toLatin1().constData());
if (!name.isEmpty()) {
return QObject::property(name.toLatin1().constData());
}
return QVariant();
}
qint64 Entity::getId() const {
src/entity.h
const QHash<QString, QMetaProperty> getInheritedMetaProperties() const;
const QHash<Relation, QMetaProperty> getRelationProperties() const;
const char *getClassname() const;
QVariant property(const QString &name) const;
qint64 getId() const;
src/entitymanager.cpp
void EntityManager::init() {
auto schema = Database::getSchema(Database::getDatabaseType(
this->db.data()->getDatabase().driverName()), this->db);
this->db->getDatabase().driverName()), this->db);
this->schema = QSharedPointer<Schema>(schema);
this->schema.data()->setTables(this->schema.data()->getTableSchemas());
this->schema->setTables(this->schema->getTableSchemas());
}
EntityManager::~EntityManager() {
......
QHash<QString, QVariant> map = QHash<QString, QVariant>();
bool ok = true;
map.insert("version", version);
if (!this->schema.data()->getTableNames().contains(dbm->getTablename())) {
if (!this->schema->getTableNames().contains(dbm->getTablename())) {
this->createTable(ptrDbm, true);
}
if (this->findAllByAttributes(map, dbm->getTablename()).isEmpty()) {
......
dbm->setApplyTime(QDateTime::currentDateTime());
this->create(ptrDbm);
}
this->schema.data()->setTables(this->schema.data()->getTableSchemas());
this->schema->setTables(this->schema->getTableSchemas());
}
return ok;
}
bool EntityManager::executeQuery(const QString &query) {
return this->db.data()->transaction(query);
return this->db->transaction(query);
}
bool EntityManager::checkTable(const QSharedPointer<Entity> &entity) {
bool rc = true;
if (!this->schema.data()->containsTable(entity.data()->getTablename())) {
if (this->schema.data()->getQueryBuilder().data()->createTable(entity)) {
this->schema.data()->getTableSchema(entity.data()->getTablename(), true);
rc = this->schema.data()->getTables().contains(entity.data()->getTablename());
if (!this->schema->containsTable(entity->getTablename())) {
if (this->schema->getQueryBuilder()->createTable(entity)) {
this->schema->getTableSchema(entity->getTablename(), true);
rc = this->schema->getTables().contains(entity->getTablename());
}
}
return rc;
......
}
void EntityManager::refresh(QSharedPointer<Entity> &entity) {
entity = this->findById(entity.data()->property(
entity.data()->getPrimaryKey()).toLongLong(),
QString(entity.data()->getClassname()));
entity = this->findById(entity->property(
entity->getPrimaryKey()).toLongLong(),
QString(entity->getClassname()));
}
void EntityManager::setSchema(const QSharedPointer<Schema> &value) {
......
const bool refresh) {
QSharedPointer<Entity> r;
if (!e.isNull()) {
if (refresh || !(r = this->cache.get(id, QString(e.data()->getClassname())))) {
e.data()->setId(id);
if (refresh || !(r = this->cache.get(id, QString(e->getClassname())))) {
e->setId(id);
auto map = this->findByPk(id, e);
r = this->convert(map, e->getClassname(), refresh);
}
......
void EntityManager::oneToMany(const QSharedPointer<Entity> &entity,
const Relation &r,
const QMetaProperty &property, const bool refresh) {
if (entity.data() && entity.data()->getId() > -1) {
if (entity.data() && entity->getId() > -1) {
Entity *e = EntityInstanceFactory::createInstance(
EntityInstanceFactory::extractEntityType(
property.typeName()));
QSqlQuery q = this->schema.data()->getQueryBuilder().data()->oneToMany(
QSqlQuery q = this->schema->getQueryBuilder()->oneToMany(
e->getTablename(),
this->schema.data()->getQueryBuilder().data()->generateColumnNameID(
r.getMappedBy()), entity.data()->getId());
this->schema->getQueryBuilder()->generateColumnNameID(
r.getMappedBy()), entity->getId());
auto listMap = this->convertQueryResult(q);
auto entities = this->convert(listMap, e->getClassname(), refresh);
delete e;
......
Entity *e = EntityInstanceFactory::createInstance(
EntityInstanceFactory::extractEntityType(
property.typeName()));
QSqlQuery q = this->schema.data()->getQueryBuilder().data()->oneToMany(
QSqlQuery q = this->schema->getQueryBuilder()->oneToMany(
e->getTablename(),
this->schema.data()->getQueryBuilder().data()->generateColumnNameID(
this->schema->getQueryBuilder()->generateColumnNameID(
r.getMappedBy()),
entity.data()->property(entity.data()->getPrimaryKey()).toLongLong(), 1);
entity->property(entity->getPrimaryKey()).toLongLong(), 1);
auto listMap = this->convertQueryResult(q);
auto entities = this->convert(listMap, e->getClassname(), refresh);
if (!entities.isEmpty()) {
......
void EntityManager::setProperty(const QSharedPointer<Entity> &entiy,
QSharedPointer<Entity> value,
const QMetaProperty &property) const {
if (value && value.data()->property(value.data()->getPrimaryKey()).toLongLong()
if (value && value->property(value->getPrimaryKey()).toLongLong()
> -1) {
property.write(entiy.data(), QVariant(value));
}
}
void EntityManager::saveRelations(const QSharedPointer<Entity> &entity) {
auto relations = entity.data()->getRelationProperties();
auto relations = entity->getRelationProperties();
auto iterator = relations.constBegin();
while (iterator != relations.constEnd()) {
const Relation r = iterator.key();
......
|| r.getCascadeType().contains(MERGE)
|| r.getCascadeType().contains(PERSIST) ? this->saveRelationEntities(list,
r) : list;
auto builder = this->schema.data()->getQueryBuilder();
q = builder.data()->manyToManyInsert(tblName,
builder.data()->generateManyToManyColumnName(entity),
builder.data()->generateManyToManyColumnName(ptr));
q.bindValue(0, entity.data()->getId());
auto builder = this->schema->getQueryBuilder();
q = builder->manyToManyInsert(tblName,
builder->generateManyToManyColumnName(entity),
builder->generateManyToManyColumnName(ptr));
q.bindValue(0, entity->getId());
QMetaProperty prop;
bool first = true;
for (int var = 0; var < saved.size(); ++var) {
ptr = list.at(var);
if (first && !r.getMappedBy().isEmpty()) {
auto props = ptr.data()->getMetaProperties();
auto props = ptr->getMetaProperties();
if (props.contains(r.getMappedBy())) {
prop = props.value(r.getMappedBy());
}
}
if (ptr.data()->property(ptr.data()->getPrimaryKey()).toLongLong() > -1) {
q.bindValue(1, ptr.data()->property(ptr.data()->getPrimaryKey()));
if (ptr->property(ptr->getPrimaryKey()).toLongLong() > -1) {
q.bindValue(1, ptr->property(ptr->getPrimaryKey()));
q.exec();
if (prop.isValid()) {
this->addEntityToListProperty(entity, ptr, prop);
......
bool EntityManager::shouldBeSaved(QSharedPointer<Entity> &entity,
const Relation &r) {
return entity && (r.getCascadeType().contains(ALL)
|| (entity.data()->property(entity.data()->getPrimaryKey()) > -1
|| (entity->property(entity->getPrimaryKey()) > -1
&& r.getCascadeType().contains(MERGE))
|| (entity.data()->property(entity.data()->getPrimaryKey()) <= -1
|| (entity->property(entity->getPrimaryKey()) <= -1
&& r.getCascadeType().contains(PERSIST)));
}
void EntityManager::removeRelations(const QSharedPointer<Entity> &entity) {
auto props = entity.data()->getRelationProperties();
auto props = entity->getRelationProperties();
auto iterator = props.constBegin();
while (iterator != props.constEnd()) {
const Relation r = iterator.key();
......
if (!var.isNull() && var.canConvert<QList<QSharedPointer<Entity>>>()) {
auto list = qvariant_cast<QList<QSharedPointer<Entity>>>(var);
if (!list.isEmpty()) {
auto metas = list.at(0).data()->getMetaProperties();
auto metas = list.at(0)->getMetaProperties();
if (metas.contains(r.getMappedBy())) {
for (int var = 0; var < list.size(); ++var) {
auto entity = list.at(var);
......
} else if (!r.getMappedBy().isEmpty()) {
if (!var.isNull() && var.canConvert<QSharedPointer<Entity>>()) {
auto e = qvariant_cast<QSharedPointer<Entity>>(var);
auto metas = e.data()->getMetaProperties();
auto metas = e->getMetaProperties();
if (metas.contains(r.getMappedBy())) {
this->setProperty(e, QSharedPointer<Entity>(), metas.value(r.getMappedBy()));
this->save(e);
......
QList<QSharedPointer<Entity>> list =
qvariant_cast<QList<QSharedPointer<Entity>>>(var);
if (!list.isEmpty()) {
auto builder = this->schema.data()->getQueryBuilder();
auto builder = this->schema->getQueryBuilder();
auto ptr = list.at(0);
QString tblName = builder.data()->generateManyToManyTableName(e, ptr);
if (this->schema.data()->getTables().contains(tblName)) {
QSqlQuery q = builder.data()->manyToManyDelete(
tblName, builder.data()->generateManyToManyColumnName(e),
e.data()->property(e.data()->getPrimaryKey()).toLongLong());
QString tblName = builder->generateManyToManyTableName(e, ptr);
if (this->schema->getTables().contains(tblName)) {
QSqlQuery q = builder->manyToManyDelete(
tblName, builder->generateManyToManyColumnName(e),
e->property(e->getPrimaryKey()).toLongLong());
bool refresh = r.getCascadeType().contains(REFRESH)
|| r.getCascadeType().contains(ALL);
bool remove = r.getCascadeType().contains(REMOVE)
......
}
void EntityManager::persistManyToMany(const QSharedPointer<Entity> &entity,
const Relation &r, const QVariant &property) {
const Relation &r, QVariant &property) {
Q_UNUSED(r)
auto list = property.value<QList<QVariant>>();
if (!list.isEmpty()) {
/**
* TODO
*/
auto ptr = list.at(0).value<QSharedPointer<Entity>>();
auto builder = this->schema.data()->getQueryBuilder();
QString tblName = builder.data()->generateManyToManyTableName(entity, ptr);
if (this->schema.data()->getTables().contains(tblName)) {
QSqlQuery q = builder.data()->manyToManyDelete(
tblName, builder.data()->generateManyToManyColumnName(entity),
entity.data()->property(entity.data()->getPrimaryKey()).toLongLong());
if (this->db.data()->transaction(q)) {
//this->persistMappedByRelation(list, q, entity, r, tblName);
if (!list.at(0).isNull()) {
QVariant var = list.at(0);
auto ptr = *reinterpret_cast<QSharedPointer<Entity>*>(var.data());
auto builder = this->schema->getQueryBuilder();
QString tblName = builder->generateManyToManyTableName(entity, ptr);
if (this->schema->getTables().contains(tblName)) {
QSqlQuery q = builder->manyToManyDelete(
tblName, builder->generateManyToManyColumnName(entity),
entity->property(entity->getPrimaryKey()).toLongLong());
if (this->db->transaction(q)) {
auto nList = *reinterpret_cast<QList<QSharedPointer<Entity>>*>(property.data());
this->persistMappedByRelation(nList, q, entity, r, tblName);
}
} else {
qDebug() << "MANY_TO_MANY Table " << tblName << " not exists";
}
} else {
qDebug() << "MANY_TO_MANY Table " << tblName << " not exists";
}
}
}
......
EntityInstanceFactory::extractEntityType(
QString(
property.typeName())));
auto builder = this->schema.data()->getQueryBuilder();
auto builder = this->schema->getQueryBuilder();
if (secEntity) {
QSharedPointer<Entity> secEntityPtr = QSharedPointer<Entity>(secEntity);
QString tblName = builder.data()->generateManyToManyTableName(entity,
QString tblName = builder->generateManyToManyTableName(entity,
secEntityPtr);
/**
* maybe it would be better, to fetch first the ids, look up cache and then request missing entities
* with this it would be also possible to respect cascade type
*/
if (this->schema.data()->getTables().contains(tblName)) {
QSqlQuery q = builder.data()->manyToMany(tblName,
builder.data()->generateManyToManyColumnName(entity),
entity.data()->property(entity.data()->getPrimaryKey()).toLongLong(),
builder.data()->generateManyToManyColumnName(secEntityPtr),
secEntityPtr.data()->getTablename());
if (this->schema->getTables().contains(tblName)) {
QSqlQuery q = builder->manyToMany(tblName,
builder->generateManyToManyColumnName(entity),
entity->property(entity->getPrimaryKey()).toLongLong(),
builder->generateManyToManyColumnName(secEntityPtr),
secEntityPtr->getTablename());
auto listMap = this->convertQueryResult(q);
auto entities = this->convert(listMap, entity.data()->getClassname(), refresh);
auto entities = this->convert(listMap, entity->getClassname(), refresh);
this->setListProperty(entity, entities, property);
} else {
qDebug() << "MANY_TO_MANY Table " << tblName << " not exists";
......
&entity,
bool ignoreID) {
auto maps = this->findAllByAttributes(entity, ignoreID);
return this->convert(maps, entity.data()->getClassname());
return this->convert(maps, entity->getClassname());
}
/**
......
const bool persistRelations, const bool checkDuplicate) {
bool rc = false;
if (this->checkTable(entity) && !(checkDuplicate && this->count(entity) == 0)) {
QList<QSqlQuery> q = this->schema.data()->getQueryBuilder().data()->create(
QList<QSqlQuery> q = this->schema->getQueryBuilder()->create(
entity);
this->db->startTransaction();
bool first = true;
for (int var = 0; var < q.size(); ++var) {
auto query = q.at(var);
rc = this->db.data()->exec(query);
rc = this->db->exec(query);
if (!rc) {
qDebug() << "Query failed:" << query.lastError().text() << " of class " <<
entity.data()->getClassname();
entity->getClassname();
break;
}
if (first) {
entity.data()->setProperty(
entity.data()->getPrimaryKey().toLatin1().constData(), query.lastInsertId());
entity->setProperty(
entity->getPrimaryKey().toLatin1().constData(), query.lastInsertId());
first = false;
}
}
if (!rc || !this->db->commitTransaction()) {
this->db->rollbackTransaction();
entity.data()->setId(-1);
entity->setId(-1);
rc = false;
} else {
if (persistRelations) {
......
bool EntityManager::merge(QSharedPointer<Entity> &entity, bool withRelations) {
if (entity->getId() > -1 && this->count(entity) == 1) {
this->db->startTransaction();
QList<QSqlQuery> q = this->schema.data()->getQueryBuilder().data()->merge(
QList<QSqlQuery> q = this->schema->getQueryBuilder()->merge(
entity);
bool ok = true;
for (int var = 0; var < q.size(); ++var) {
auto query = q.at(var);
ok = this->db.data()->exec(query);
ok = this->db->exec(query);
if (!ok) {
qDebug() << query.lastError().text();
break;
......
QHash<QString, QVariant> EntityManager::findByPk(qint64 id,
const QSharedPointer<Entity>
&e) {
QSqlQuery q = this->schema.data()->getQueryBuilder().data()->find(id, e, 0,
e.data()->getPrimaryKey());
QSqlQuery q = this->schema->getQueryBuilder()->find(id, e, 0,
e->getPrimaryKey());
auto listMap = this->convertQueryResult(q);
if (!listMap.isEmpty()) {
return listMap.at(0);
......
const QSharedPointer<Entity>
&entity,
bool ignoreID) {
QSqlQuery q = this->schema.data()->getQueryBuilder().data()->findByAttributes(
QSqlQuery q = this->schema->getQueryBuilder()->findByAttributes(
entity, ignoreID);
return this->convertQueryResult(q);
}
QList<QHash <QString, QVariant> > EntityManager::findAllByAttributes(
const QHash<QString, QVariant> &m, const QString &tblname, bool ignoreID) {
QSqlQuery q = this->schema.data()->getQueryBuilder().data()->findByAttributes(m,
QSqlQuery q = this->schema->getQueryBuilder()->findByAttributes(m,
tblname, ignoreID);
return this->convertQueryResult(q);
}
......
QList<QHash <QString, QVariant> > EntityManager::findAll(
const QSharedPointer<Entity> &e) {
QSqlQuery q = this->schema.data()->getQueryBuilder().data()->findAll(e);
QSqlQuery q = this->schema->getQueryBuilder()->findAll(e);
return this->convertQueryResult(q);
}
void EntityManager::resolveRelations(const QSharedPointer<Entity> &entity,
const QHash<QString, QVariant> &map, const bool refresh) {
auto props = entity.data()->getRelationProperties();
auto props = entity->getRelationProperties();
auto iterator = props.constBegin();
while (iterator != props.constEnd()) {
const Relation r = iterator.key();
......
switch (r.getType()) {
case MANY_TO_ONE:
if (map.contains(
this->schema.data()->getQueryBuilder().data()->generateColumnNameID(
this->schema->getQueryBuilder()->generateColumnNameID(
r.getPropertyName()))) {
this->manyToOne(entity, property.read(entity.data()), property, refresh);
}
......
bool EntityManager::save(QSharedPointer<Entity> &entity,
const bool persistRelations) {
if (entity.data()->property(entity.data()->getPrimaryKey()) > -1) {
if (entity->property(entity->getPrimaryKey()) > -1) {
return this->merge(entity, persistRelations);
} else {
return this->create(entity, persistRelations);
......
qint64 EntityManager::findId(QSharedPointer<Entity> &entity) {
qint64 r = -1;
QSqlQuery q = this->schema.data()->getQueryBuilder().data()->findId(entity);
QSqlQuery q = this->schema->getQueryBuilder()->findId(entity);
this->db->select(q);
if (q.next()) {
r = q.value(0).toLongLong();
......
bool rc = false;
this->db->startTransaction();
this->removeRelations(entity);
auto queries = this->schema.data()->getQueryBuilder().data()->remove(entity);
auto queries = this->schema->getQueryBuilder()->remove(entity);
bool ok = true;
for (int var = 0; var < queries.size(); ++var) {
auto q = queries.at(var);
......
}
bool EntityManager::removeAll(QString tblname) {
return this->schema.data()->getQueryBuilder().data()->removeAll(tblname).exec();
return this->schema->getQueryBuilder()->removeAll(tblname).exec();
}
bool EntityManager::createTable(const QSharedPointer<Entity> &entity,
bool createRelationTables) {
return this->schema.data()->getQueryBuilder().data()->createTable(entity,
return this->schema->getQueryBuilder()->createTable(entity,
createRelationTables);
}
......
qint8 EntityManager::count(const QSharedPointer<Entity> &entity,
bool ignoreID) {
qint8 rc = -1;
QSqlQuery q = this->schema.data()->getQueryBuilder().data()->count(entity,
QSqlQuery q = this->schema->getQueryBuilder()->count(entity,
ignoreID);
this->db->select(q);
if (q.next()) {
......
qint8 EntityManager::count(const QString &tableName) {
qint8 rc = -1;
QSqlQuery q = this->schema.data()->getQueryBuilder().data()->count(tableName);
QSqlQuery q = this->schema->getQueryBuilder()->count(tableName);
this->db->select(q);
if (q.next()) {
rc = q.value(0).toInt();
src/entitymanager.h
bool canPersistRelation(const Relation &relation, const RelationType &r,
const QVariant &var) const;
void persistManyToMany(const QSharedPointer<Entity> &entity, const Relation &r,
const QVariant &property);
QVariant &property);
QList<QHash<QString, QVariant> > findAllByAttributes(const
QSharedPointer<Entity> &entity,
bool ignoreID = false);
......
Entity *e = EntityInstanceFactory::createInstance<T>();
if (e) {
QSharedPointer<Entity> ptr = QSharedPointer<Entity>(e);
e->setId(id);
ptr->setId(id);
return this->remove(ptr);
}
return false;
......
};
}
Q_DECLARE_METATYPE(QSharedPointer<CuteEntityManager::Entity>)
#endif // ENTITYMANAGER_H
src/querybuilder.cpp
bool rc = false;
if (entity.data()) {
auto tableDefinition = this->generateTableDefinition(entity);
QString tableName = entity.data()->getTablename();
this->schema.data()->containsTable(tableName) ? rc = true : rc = false;
QString tableName = entity->getTablename();
this->schema->containsTable(tableName) ? rc = true : rc = false;
if (!rc) {
QSqlQuery q = this->database.data()->getQuery(this->createTable(tableName,
tableDefinition));
if (this->database.data()->transaction(q)) {
QSqlQuery q = this->database->getQuery(this->createTable(tableName,
tableDefinition));
if (this->database->transaction(q)) {
if (createRelationTables) {
auto relTables = this->generateRelationTables(entity);
auto i = relTables.constBegin();
while (i != relTables.constEnd()) {
auto query = this->database.data()->getQuery(this->createTable(i.key(),
i.value()));
this->database.data()->exec(query);
auto query = this->database->getQuery(this->createTable(i.key(),
i.value()));
this->database->exec(query);
++i;
}
}
this->schema.data()->getTableSchema(tableName);
this->schema->getTableSchema(tableName);
rc = true;
if (rc) {
rc = this->createIndices(entity);
......
}
bool QueryBuilder::createIndices(const QSharedPointer<Entity> &entity) const {
Entity *e = entity.data();
bool ok = true;
QStringList queries = QStringList();
QString superIndex = this->createFkSuperClass(e);
QString superIndex = this->createFkSuperClass(entity.data());
if (!superIndex.isEmpty()) {
queries.append(superIndex);
}
queries.append(this->relationFks(entity));
ok = this->database.data()->transaction(queries);
ok = this->database->transaction(queries);
return ok;
}
......
const {
QStringList queries = QStringList();
if (this->supportsForeignKeys()) {
auto relations = entity.data()->getNonInheritedRelations();
auto props = entity.data()->getMetaProperties();
auto relations = entity->getNonInheritedRelations();
auto props = entity->getMetaProperties();
auto iterator = relations.constBegin();
while (iterator != relations.constEnd()) {
auto relation = iterator.value();
......
const QString &remove) const {
QSharedPointer<Entity> ptr = QSharedPointer<Entity>
(EntityInstanceFactory::createInstance(metaProperty.type()));
if (ptr.data()) {
if (ptr) {
if (relation.getType() == ONE_TO_ONE || relation.getType() == MANY_TO_ONE) {
QString indexName = this->generateIndexName(relation.getPropertyName(),
entity.data()->getTablename(),
entity->getTablename(),
this->generateColumnNameID(relation.getPropertyName()),
ptr.data()->getTablename(), true);
queries.append(this->addForeignKey(indexName, entity.data()->getTablename(),
ptr->getTablename(), true);
queries.append(this->addForeignKey(indexName, entity->getTablename(),
QStringList(this->generateColumnNameID(relation.getPropertyName())),
ptr.data()->getTablename(),
QStringList(ptr.data()->getPrimaryKey()), remove, update));
ptr->getTablename(),
QStringList(ptr->getPrimaryKey()), remove, update));
} else if (relation.getType() == MANY_TO_MANY) {
QString tableName = this->generateManyToManyTableName(entity, ptr);
......
QString fkColumn = this->generateManyToManyColumnName(entity);
QString indexName = this->generateIndexName(fkColumn,
tableName, fkColumn,
entity.data()->getTablename(), true);
entity->getTablename(), true);
return this->addForeignKey(indexName, tableName, QStringList(fkColumn),
entity.data()->getTablename(), QStringList(entity.data()->getPrimaryKey()),
entity->getTablename(), QStringList(entity->getPrimaryKey()),
remove, update);
}
......
const QHash<QString, QString> &tableDefinition) const {
bool first = true;
QString s = "CREATE TABLE ";
s.append(this->schema.data()->quoteTableName(tableName).append(" (\n"));
s.append(this->schema->quoteTableName(tableName).append(" (\n"));
auto i = tableDefinition.constBegin();
while (i != tableDefinition.constEnd()) {
if (first) {
......
} else {
s.append(", ");
}
s.append(this->schema.data()->quoteColumnName(i.key())).append(" " +
s.append(this->schema->quoteColumnName(i.key())).append(" " +
this->getColumnType(
i.value()));
++i;
......
}
QString QueryBuilder::renameTable(QString tableName, QString newName) const {
return "RENAME TABLE " + this->schema.data()->quoteTableName(
return "RENAME TABLE " + this->schema->quoteTableName(
tableName) + " TO " +
this->schema.data()->quoteTableName(
this->schema->quoteTableName(
newName);
}
QString QueryBuilder::dropTable(QString tableName) const {
return "DROP TABLE " + this->schema.data()->quoteTableName(tableName);
return "DROP TABLE " + this->schema->quoteTableName(tableName);
}
QString QueryBuilder::truncateTable(QString tableName) const {
return "TRUNCATE TABLE " + this->schema.data()->quoteTableName(tableName);
return "TRUNCATE TABLE " + this->schema->quoteTableName(tableName);
}
QString QueryBuilder::addColumn(QString tableName, QString columnName,
QString columnType) const {
return "ALTER TABLE " + this->schema.data()->quoteTableName(
return "ALTER TABLE " + this->schema->quoteTableName(
tableName) + " ADD " +
this->schema.data()->quoteColumnName(
this->schema->quoteColumnName(
columnName) + " " + this->getColumnType(columnType);
}
QString QueryBuilder::dropColumn(QString tableName, QString columName) const {
return "ALTER TABLE " + this->schema.data()->quoteTableName(
return "ALTER TABLE " + this->schema->quoteTableName(
tableName) + " DROP COLUMN " +
this->schema.data()->quoteColumnName(columName);
this->schema->quoteColumnName(columName);
}
QString QueryBuilder::renameColumn(QString tableName, QString oldName,
QString newName) const {
return "ALTER TABLE " + this->schema.data()->quoteTableName(
return "ALTER TABLE " + this->schema->quoteTableName(
tableName) + " RENAME COLUMN " +
this->schema.data()->quoteColumnName(oldName) + " TO " +
this->schema.data()->quoteColumnName(
this->schema->quoteColumnName(oldName) + " TO " +
this->schema->quoteColumnName(
newName);
}
QString QueryBuilder::alterColumn(QString tableName, QString columnName,
QString newType) const {
return "ALTER TABLE " + this->schema.data()->quoteTableName(
return "ALTER TABLE " + this->schema->quoteTableName(
tableName) + " CHANGE " +
this->schema.data()->quoteColumnName(columnName) + " " +
this->schema.data()->quoteColumnName(columnName) + this->getColumnType(newType);
this->schema->quoteColumnName(columnName) + " " +
this->schema->quoteColumnName(columnName) + this->getColumnType(newType);
}
QString QueryBuilder::addPrimaryKey(QString name, QString tableName,
QStringList columns) const {
return "ALTER TABLE " + this->schema.data()->quoteTableName(
return "ALTER TABLE " + this->schema->quoteTableName(
tableName) + " ADD CONSTRAINT " +
this->schema.data()->quoteColumnName(name) + "PRIMARY KEY (" +
this->schema->quoteColumnName(name) + "PRIMARY KEY (" +
this->buildColumns(columns) + " )";
}
QString QueryBuilder::dropPrimaryKey(QString name, QString tableName) const {
return "ALTER TABLE " + this->schema.data()->quoteTableName(
return "ALTER TABLE " + this->schema->quoteTableName(
tableName) + " DROP CONSTRAINT " +
this->schema.data()->quoteColumnName(name);
this->schema->quoteColumnName(name);
}
QString QueryBuilder::addForeignKey(QString name, QString tableName,
......
QString refTableName,
QStringList refColumns, QString deleteConstraint,
QString updateConstraint) const {
QString r = "ALTER TABLE " + this->schema.data()->quoteTableName(
QString r = "ALTER TABLE " + this->schema->quoteTableName(
tableName) + "ADD CONSTRAINT " +
this->schema.data()->quoteColumnName(name)
this->schema->quoteColumnName(name)
+ " FOREIGN KEY (" + this->buildColumns(columns) + ")" + " REFERENCES " +
this->schema.data()->quoteTableName(
this->schema->quoteTableName(
refTableName) +
" (" + this->buildColumns(refColumns) + ")";
if (!deleteConstraint.isEmpty()) {
......
}
QString QueryBuilder::dropForeignKey(QString name, QString tableName) const {
return "ALTER TABLE " + this->schema.data()->quoteTableName(
return "ALTER TABLE " + this->schema->quoteTableName(
tableName) + " DROP CONSTRAINT " +
this->schema.data()->quoteColumnName(name);
this->schema->quoteColumnName(name);
}
QString QueryBuilder::createIndex(QString name, QString tableName,
QStringList columns,
bool unique) const {
QString s = (unique ? "CREATE UNIQUE INDEX " : "CREATE INDEX ") +
this->schema.data()->quoteTableName(
name) + " ON " + this->schema.data()->quoteTableName(tableName) + " (";
this->schema->quoteTableName(
name) + " ON " + this->schema->quoteTableName(tableName) + " (";
s.append(this->buildColumns(columns));
s.append(");");
return s;
}
QString QueryBuilder::dropIndex(QString name, QString tableName) const {
return "DROP INDEX " + this->schema.data()->quoteTableName(name) + " ON " +
this->schema.data()->quoteTableName(
return "DROP INDEX " + this->schema->quoteTableName(name) + " ON " +
this->schema->quoteTableName(
tableName);
}
......
} else {
first = false;
}
p1 += this->schema.data()->quoteColumnName(i.key());
p1 += this->schema->quoteColumnName(i.key());
p2 += ":" + i.key();
++i;
}
......
const QSharedPointer<Entity> &entity)
const {
auto map = QHash<QString, QString>();
auto o = entity.data()->metaObject();
auto superMetaObject = entity.data()->metaObject()->superClass();
auto superMetaObjectPropertyMap = entity.data()->getSuperMetaProperties();
QHash<QString, Relation> relations = entity.data()->getRelations();
auto o = entity->metaObject();
auto superMetaObject = entity->metaObject()->superClass();
auto superMetaObjectPropertyMap = entity->getSuperMetaProperties();
QHash<QString, Relation> relations = entity->getRelations();
for (int var = 0; var < o->propertyCount(); ++var) {
auto m = o->property(var);
if (!superMetaObjectPropertyMap.contains(QString(m.name()))
&& m.name() != QString("objectName") && m.isReadable()
&& !entity.data()->getTransientAttributes().contains(m.name())) {
&& !entity->getTransientAttributes().contains(m.name())) {
if (m.isEnumType()) {
map.insert(m.name(), this->schema.data()->getTypeMap().data()->value(
this->schema.data()->TYPE_INTEGER));
map.insert(m.name(), this->schema->getTypeMap()->value(
this->schema->TYPE_INTEGER));
} else if (relations.contains(m.name())) {
Relation r = relations.value(m.name());
if (r.getType() == RelationType::MANY_TO_ONE
|| (r.getType() == RelationType::ONE_TO_ONE
&& r.getMappedBy().isEmpty())) {
map.insert(this->generateColumnNameID(QString(m.name())),
this->schema.data()->TYPE_BIGINT);
this->schema->TYPE_BIGINT);
}
} else if (entity.data()->getBLOBColumns().contains(m.name())) {
map.insert(m.name(), this->schema.data()->getTypeMap().data()->value(
this->schema.data()->TYPE_BINARY));
} else if (entity->getBLOBColumns().contains(m.name())) {
map.insert(m.name(), this->schema->getTypeMap()->value(
this->schema->TYPE_BINARY));
} else {
map.insert(m.name(), this->transformAbstractTypeToRealDbType(
this->transformTypeToAbstractDbType(
......
}
if (!(QString(superMetaObject->className()) !=
QString("CuteEntityManager::Entity")
&& entity.data()->getInheritanceStrategy() == JOINED_TABLE)) {
map.insert(entity.data()->getPrimaryKey(), this->schema.data()->TYPE_BIGPK);
&& entity->getInheritanceStrategy() == JOINED_TABLE)) {
map.insert(entity->getPrimaryKey(), this->schema->TYPE_BIGPK);
}
return map;
}
......
QString QueryBuilder::generateManyToManyTableName(const QSharedPointer<Entity>
&firstEntity,
const QSharedPointer<Entity> &secondEntity) const {
QString first = QString(firstEntity.data()->getClassname());
QString second = QString(secondEntity.data()->getClassname());
QString first = QString(firstEntity->getClassname());
QString second = QString(secondEntity->getClassname());
if (QString::compare(first, second, Qt::CaseSensitive) <= 0) {
return firstEntity.data()->getTablename() + "_" +
secondEntity.data()->getTablename();
return firstEntity->getTablename() + "_" +
secondEntity->getTablename();
} else {
return secondEntity.data()->getTablename() + "_" +
firstEntity.data()->getTablename();
return secondEntity->getTablename() + "_" +
firstEntity->getTablename();
}
}
......
const QSharedPointer<Entity> &entity)
const {
auto relations = QHash<QString, QHash<QString, QString>>();
QHash<QString, Relation> m = entity.data()->getRelations();
auto props = entity.data()->getMetaProperties();
QHash<QString, Relation> m = entity->getRelations();
auto props = entity->getMetaProperties();
for (auto i = m.begin(); i != m.end(); ++i) {
Relation r = i.value();
if (r.getType() == MANY_TO_MANY && r.getMappedBy().isEmpty()) {
QHash<QString, QString> h = QHash<QString, QString>();
h.insert(entity.data()->getPrimaryKey(), this->schema.data()->TYPE_BIGPK);
h.insert(entity->getPrimaryKey(), this->schema->TYPE_BIGPK);
h.insert(this->generateManyToManyColumnName(entity),
this->schema.data()->TYPE_BIGINT);
this->schema->TYPE_BIGINT);
auto meta = props.value(r.getPropertyName());
QSharedPointer<Entity> ptr = QSharedPointer<Entity>
(EntityInstanceFactory::createInstance(EntityInstanceFactory::extractEntityType(
QMetaType::typeName(meta.userType()))));
h.insert(this->generateManyToManyColumnName(ptr),
this->schema.data()->TYPE_BIGINT);
this->schema->TYPE_BIGINT);
relations.insert(this->generateManyToManyTableName(entity, ptr), h);
}
}
......
QString QueryBuilder::transformTypeToAbstractDbType(QString typeName) const {
QHash<QString, QString> *m = this->schema.data()->getAbstractTypeMap().data();
QHash<QString, QString> *m = this->schema->getAbstractTypeMap().data();
if (m->contains(typeName)) {
return m->value(typeName);
}
......
return i.value();
}
}
return this->schema.data()->TYPE_TEXT;
return this->schema->TYPE_TEXT;
}
QString QueryBuilder::transformAbstractTypeToRealDbType(
QString typeName) const {
return this->schema.data()->getTypeMap().data()->value(typeName);
return this->schema->getTypeMap()->value(typeName);
}
QString QueryBuilder::getColumnType(const QString &type) const {
/**
* @WARNING
*/
QHash<QString, QString> *tMap = this->schema.data()->getTypeMap().data();
QHash<QString, QString> *tMap = this->schema->getTypeMap().data();
if (tMap->contains(type)) {
return this->transformAbstractTypeToRealDbType(type);
}
......
* @return
*/
QSqlQuery QueryBuilder::find(const qint64 &id, const QString &tableName) const {
QSqlQuery q = this->database.data()->getQuery(this->selectBase(QStringList(
tableName)) + " WHERE id= :id LIMIT 1;");
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
tableName)) + " WHERE id= :id LIMIT 1;");
q.bindValue(":id", id);
return q;
}
......
if (var != 0) {
r.append(" ");
}
r.append(this->schema.data()->quoteColumnName(columns.at(var)));
r.append(this->schema->quoteColumnName(columns.at(var)));
}
}
r.append(" FROM");
for (int var = 0; var < tables.size(); ++var) {
r.append(" ");
r.append(this->schema.data()->quoteTableName(tables.at(var)));
r.append(this->schema->quoteTableName(tables.at(var)));
}
return r;
}
QSqlQuery QueryBuilder::find(const qint64 &id,
const QSharedPointer<Entity> &entity, qint64 offset, QString pk) const {
QSqlQuery q = this->database.data()->getQuery(this->selectBase(QStringList(
entity.data()->getTablename())) + this->joinSuperClasses(
entity) + " WHERE " + this->schema.data()->quoteColumnName(
pk) + "= :id" + this->limit(1, offset));
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
entity->getTablename())) + this->joinSuperClasses(
entity) + " WHERE " + this->schema->quoteColumnName(
pk) + "= :id" + this->limit(1, offset));
q.bindValue(":id", id);
return q;
}
......
QSqlQuery QueryBuilder::findAll(const QSharedPointer<Entity> &entity,
const qint64 limit, qint64 offset) {
return this->database->getQuery(this->selectBase(QStringList(
entity.data()->getTablename())) + " " + this->joinSuperClasses(
entity->getTablename())) + " " + this->joinSuperClasses(
entity) + this->limit(limit, offset) + ";");
}
......
QSqlQuery QueryBuilder::findByAttributes(const QHash<QString, QVariant> &m,
const QString &tableName,
const bool &ignoreID, const qint64 limit, const qint64 offset) const {
QSqlQuery q = this->database.data()->getQuery(this->selectBase(QStringList(
tableName)) + this->where(m, "AND", ignoreID) + this->limit(limit, offset));
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
tableName)) + this->where(m, "AND", ignoreID) + this->limit(limit, offset));
this->bindValues(m, q, ignoreID);
return q;
}
......
const qint64 limit,
const qint64 offset) {
QHash<QString, QVariant> values = this->getEntityAttributes(
e.data()->getMetaProperties(), e);
return this->findByAttributes(values, e.data()->getTablename(), ignoreID, limit,
e->getMetaProperties(), e);
return this->findByAttributes(values, e->getTablename(), ignoreID, limit,
offset);
}
......
QList<QSqlQuery> QueryBuilder::remove(const QSharedPointer<Entity> &entity)
const {
QList<QSqlQuery> queries = QList<QSqlQuery>();
queries.append(this->remove(entity.data()->getTablename(),
entity.data()->property(entity.data()->getPrimaryKey()).toLongLong()));
if (entity.data()->getInheritanceStrategy() != PER_CLASS_TABLE
&& entity.data()->isInheritanceCascaded()) {
auto classes = entity.data()->superClasses(true);
queries.append(this->remove(entity->getTablename(),
entity->property(entity->getPrimaryKey()).toLongLong()));
if (entity->getInheritanceStrategy() != PER_CLASS_TABLE
&& entity->isInheritanceCascaded()) {
auto classes = entity->superClasses(true);
for (int var = 0; var < classes.size(); ++var) {
auto item = classes.at(var);
auto instance = EntityInstanceFactory::createInstance(item->className());
if (instance) {
queries.append(this->remove(instance->getTablename(),
entity.data()->property(entity.data()->getPrimaryKey()).toLongLong()));
entity->property(entity->getPrimaryKey()).toLongLong()));
delete instance;
instance = 0;
}
......
QSqlQuery QueryBuilder::remove(const QString &tableName,
const qint64 &id, const QString &primaryKey) const {
QSqlQuery q = this->database->getQuery("DELETE FROM " +
this->schema.data()->quoteTableName(
this->schema->quoteTableName(
tableName) + " WHERE " +
this->schema.data()->quoteColumnName(primaryKey) + "=:id;");
this->schema->quoteColumnName(primaryKey) + "=:id;");
q.bindValue(":id", id);
return q;
}
QSqlQuery QueryBuilder::findId(const QSharedPointer<Entity> &entity) const {
QHash<QString, QVariant> values = this->getEntityAttributes(
entity.data()->getMetaProperties(),
entity->getMetaProperties(),
entity);
QSqlQuery q = this->database.data()->getQuery(this->selectBase(QStringList(
entity.data()->getTablename()),
QStringList(entity.data()->getPrimaryKey())) + this->where(values,
"AND", true) + " LIMIT 1");
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
entity->getTablename()),
QStringList(entity->getPrimaryKey())) + this->where(values,
"AND", true) + " LIMIT 1");
this->bindValues(values, q);
return q;
}
......
QSqlQuery QueryBuilder::count(const QSharedPointer<Entity> &entity,
bool ignoreID) const {
QHash<QString, QVariant> values = this->getEntityAttributes(
entity.data()->getMetaProperties(),
entity->getMetaProperties(),
entity);
QSqlQuery q = this->database.data()->getQuery(this->selectBase(QStringList(
entity.data()->getTablename()),
QStringList(this->countFunction())) + this->where(
values, "AND", ignoreID));
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
entity->getTablename()),
QStringList(this->countFunction())) + this->where(
values, "AND", ignoreID));
this->bindValues(values, q, ignoreID);
return q;
}
QSqlQuery QueryBuilder::count(const QString &tableName) const {
QSqlQuery q = this->database.data()->getQuery(this->selectBase(QStringList(
tableName), QStringList(this->countFunction())) + ";");
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
tableName), QStringList(this->countFunction())) + ";");
return q;
}
......
}
QSqlQuery QueryBuilder::removeAll(const QString &tableName) const {
return this->database.data()->getQuery(this->truncateTable(tableName));
return this->database->getQuery(this->truncateTable(tableName));
}
QSqlQuery QueryBuilder::insert(const QString &tableName,
......
// } else {
attributes.remove(primaryKey);
// }
QSqlQuery q = this->database.data()->getQuery();
QString p1 = "INSERT INTO " + this->schema.data()->quoteTableName(
QSqlQuery q = this->database->getQuery();
QString p1 = "INSERT INTO " + this->schema->quoteTableName(
tableName) + "(";
QString p2 = "VALUES(";
if (!attributes.isEmpty()) {
......
QSqlQuery QueryBuilder::update(const QString &tableName,
QHash<QString, QVariant> &attributes, const QString &primaryKey) const {
QSqlQuery q = this->database.data()->getQuery("UPDATE " +
this->schema.data()->quoteTableName(tableName) + " SET " + this->attributes(
attributes) + " WHERE " + this->schema.data()->quoteColumnName(
primaryKey) + "=:id;");
QSqlQuery q = this->database->getQuery("UPDATE " +
this->schema->quoteTableName(tableName) + " SET " + this->attributes(
attributes) + " WHERE " + this->schema->quoteColumnName(
primaryKey) + "=:id;");
this->bindValues(attributes, q);
return q;
}
......
const QString &attribute,
const qint64 &id,
const QString &foreignKey, const QString &foreignTable) {
QSqlQuery q = this->database.data()->getQuery();
QSqlQuery q = this->database->getQuery();
QString sql = this->selectBase(QStringList(tableName),
QStringList(foreignTable + ".*")) + " " + this->leftJoin(
foreignTable, tableName,
foreignKey) + " WHERE " + this->schema.data()->quoteColumnName(
foreignKey) + " WHERE " + this->schema->quoteColumnName(
attribute) + "=:id;";
q.prepare(sql);
q.bindValue(":id", id);
......
QSqlQuery QueryBuilder::manyToManyDelete(const QString &tableName,
const QString &attribute, const qint64 &id) {
QSqlQuery q = this->database.data()->getQuery();
QString sql = "DELETE FROM " + this->schema.data()->quoteTableName(
tableName) + " WHERE " + this->schema.data()->quoteColumnName(
QSqlQuery q = this->database->getQuery();
QString sql = "DELETE FROM " + this->schema->quoteTableName(
tableName) + " WHERE " + this->schema->quoteColumnName(
attribute) + "=:id";
q.prepare(sql);
q.bindValue(":id", id);
......
QSqlQuery QueryBuilder::manyToManyInsert(const QString &tableName,
const QString &col1, const QString &col2) const {
QSqlQuery q = this->database.data()->getQuery();
QString sql = "INSERT INTO " + this->schema.data()->quoteTableName(
QSqlQuery q = this->database->getQuery();
QString sql = "INSERT INTO " + this->schema->quoteTableName(
tableName) + "(" + col1 + "," + col2 + ")"
+ "VALUES(?, ?);";
q.prepare(sql);
......
QString QueryBuilder::joinSuperClasses(const QSharedPointer<Entity> &entity)
const {
auto classes = entity.data()->superClasses(true);
auto classes = entity->superClasses(true);
QString joined = "";
Entity *e = 0;
for (int var = 0; var < classes.size(); ++var) {
......
e = EntityInstanceFactory::createInstance(metaObject->className());
if (e) {
joined.append(" ");
joined.append(this->leftJoin(e->getTablename(), entity.data()->getTablename(),
e->getPrimaryKey(), entity.data()->getPrimaryKey()));
joined.append(this->leftJoin(e->getTablename(), entity->getTablename(),
e->getPrimaryKey(), entity->getPrimaryKey()));
}
delete e;
e = 0;
......
QString QueryBuilder::countFunction(const QString &distinctColumn) const {
return QString("COUNT(" + distinctColumn.isEmpty() ? "*" : (this->distinct() +
this->schema.data()->quoteColumnName(distinctColumn)) + ")");
this->schema->quoteColumnName(distinctColumn)) + ")");
}
QString QueryBuilder::distinct() const {
......
QString QueryBuilder::generateManyToManyColumnName(const QSharedPointer<Entity>
&entity) const {
if (entity) {
return this->generateColumnNameID(entity.data()->getTablename());
return this->generateColumnNameID(entity->getTablename());
}
qDebug() << "Entity is empty!";
return "";
}
QSqlQuery QueryBuilder::getQuery() const {
return this->database.data()->getQuery();
return this->database->getQuery();
}
......
QSharedPointer<Entity> &entity, QHash<QString, QMetaProperty> props,
QHash<QString, Relation> relations) const {
if (props.isEmpty()) {
props = entity.data()->getMetaProperties();
props = entity->getMetaProperties();
}
auto values = this->getEntityAttributes(props, entity);
auto relValues = this->getManyToOneAttributes(props, entity, relations);
......
QHash<QString, QMetaProperty> QueryBuilder::processProperties(
const QSharedPointer<Entity> &e,
QHash<QString, QMetaProperty> &usedProperties) const {
auto properties = e.data()->getMetaProperties();
auto properties = e->getMetaProperties();
QMutableHashIterator<QString, QMetaProperty> i(properties);
while (i.hasNext()) {
i.next();
if (usedProperties.contains(i.key()) && i.key() != e.data()->getPrimaryKey()) {
if (usedProperties.contains(i.key()) && i.key() != e->getPrimaryKey()) {
properties.remove(i.key());
} else {
usedProperties.insert(i.key(), i.value());
......
QHash<QString, Relation> QueryBuilder::processRelations(
const QSharedPointer<Entity> &e,
QHash<QString, Relation> &usedRelations) const {
auto relations = e.data()->getRelations();
auto relations = e->getRelations();
auto i = QMutableHashIterator<QString, Relation>(relations);
while (i.hasNext()) {
i.next();
......
QList<QueryBuilder::ClassAttributes> QueryBuilder::inheritedAttributes(
const QSharedPointer<Entity> &entity) const {
auto list = QList<QueryBuilder::ClassAttributes>();
if (entity.data()->getInheritanceStrategy() == JOINED_TABLE) {
if (entity->getInheritanceStrategy() == JOINED_TABLE) {
auto classes = QList<const QMetaObject *>();
classes.append(entity.data()->metaObject());
classes.append(entity.data()->superClasses(true));
classes.append(entity->metaObject());
classes.append(entity->superClasses(true));
auto usedProperties = QHash<QString, QMetaProperty>();
auto usedRelations = QHash<QString, Relation>();
QSharedPointer<Entity> e;
......
e = QSharedPointer<Entity>(EntityInstanceFactory::createInstance(
metaObj));
if (e) {
list.append(QueryBuilder::ClassAttributes(e.data()->getTablename(),
list.append(QueryBuilder::ClassAttributes(e->getTablename(),
this->saveAttributes(entity, this->processProperties(e, usedProperties),
this->processRelations(e, usedRelations)), e.data()->getPrimaryKey()));
this->processRelations(e, usedRelations)), e->getPrimaryKey()));
} else {
qDebug() << "Instance of " << metaObj->className() << " could not be created";
break;
}
}
} else {
list.append(QueryBuilder::ClassAttributes(entity.data()->getTablename(),
this->saveAttributes(entity), entity.data()->getPrimaryKey()));
list.append(QueryBuilder::ClassAttributes(entity->getTablename(),
this->saveAttributes(entity), entity->getPrimaryKey()));
}
return list;
}
......
QString QueryBuilder::leftJoin(const QString &foreignTable,
const QString &tableName, const QString &foreignKey,
const QString &primaryKey) const {
return "LEFT JOIN " + this->schema.data()->quoteTableName(
return "LEFT JOIN " + this->schema->quoteTableName(
foreignTable) + " ON " +
this->schema.data()->quoteColumnName(foreignTable + "." + primaryKey) + "=" +
this->schema.data()->quoteColumnName(
this->schema->quoteColumnName(foreignTable + "." + primaryKey) + "=" +
this->schema->quoteColumnName(
tableName + "." + foreignKey);
}
......
const QHash<QString, QMetaProperty>
&props,
const QSharedPointer<Entity> &entity) const {
Entity *e = entity.data();
auto map = QHash<QString, QVariant>();
auto transientAttrs = e->getTransientAttributes();
auto relations = e->getRelations();
auto transientAttrs = entity->getTransientAttributes();
auto relations = entity->getRelations();
auto i = props.constBegin();
while (i != props.constEnd()) {
if (!transientAttrs.contains(i.key()) && !relations.contains(i.key())) {
map.insert(i.key(), i.value().read(e));
map.insert(i.key(), i.value().read(entity.data()));
}
++i;
}
......
props,
const QSharedPointer<Entity> &entity,
QHash<QString, Relation> relations) const {
Entity *e = entity.data();
auto map = QHash<QString, QVariant>();
if (relations.isEmpty()) {
relations = e->getRelations();
relations = entity->getRelations();
}
auto i = relations.constBegin();
while (i != relations.constEnd()) {
Relation r = i.value();
if ((r.getType() == MANY_TO_ONE && props.contains(i.key()))
|| (r.getType() == ONE_TO_ONE && r.getMappedBy().isEmpty())) {
auto v = props.value(i.key()).read(e);
auto v = props.value(i.key()).read(entity.data());
if (v.canConvert<Entity *>()) {
this->insertRelationId(qvariant_cast<Entity *>(v), map, i.key());
} else if (v.canConvert<QSharedPointer<Entity>>()) {
......
QString QueryBuilder::where(const QSharedPointer<Entity> &entity,
QString conjunction,
bool ignoreID) const {
return this->where(this->getEntityAttributes(entity.data()->getMetaProperties(),
return this->where(this->getEntityAttributes(entity->getMetaProperties(),
entity),
conjunction, ignoreID, entity.data()->getPrimaryKey());
conjunction, ignoreID, entity->getPrimaryKey());
}
QString QueryBuilder::where(const QHash<QString, QVariant> &m,
......
if (!(rc == "")) {
rc += " " + conjunction + " ";
}
rc += this->schema.data()->quoteColumnName(i.key()) + "=:" + i.key();
rc += this->schema->quoteColumnName(i.key()) + "=:" + i.key();
}
++i;
}
src/relation.h
#include <QHash>
namespace CuteEntityManager {
enum RelationType {
ONE_TO_ONE, //e.g. specialization, heritage
ONE_TO_MANY, //@OneToMany(cascade=ALL, mappedBy="customer") e.g. QList<QSharedPointer<Person>>
MANY_TO_ONE, //e.g. QSharedPointer<Person>
ONE_TO_ONE = 0, //e.g. specialization, heritage
ONE_TO_MANY = 1, //@OneToMany(cascade=ALL, mappedBy="customer") e.g. QList<QSharedPointer<Person>>
MANY_TO_ONE = 2, //e.g. QSharedPointer<Person>
//1-n Entity foreign key in same table
MANY_TO_MANY, //e.g. QList<QSharedPointer<Person>> - realized with seperated database table
MANY_TO_MANY = 3, //e.g. QList<QSharedPointer<Person>> - realized with seperated database table
};
enum InheritanceStrategy {
......
* @param type
* @param mappedBy Q_PROPERTY in foreign Entity
*/
explicit Relation(QString propertyName, RelationType type, QString mappedBy = QString(),
QList<CascadeType> cascadeType = {MERGE, PERSIST, REFRESH});
explicit Relation(QString propertyName, RelationType type,
QString mappedBy = QString(),
QList<CascadeType> cascadeType = {MERGE, PERSIST, REFRESH});
~Relation();
RelationType getType() const;
void setType(const RelationType &value);
src/schema.cpp
void Schema::initAbstractDatabaseTypes() {
this->abstractTypeMap = QSharedPointer<QHash<QString, QString>>::create();
this->abstractTypeMap.data()->insert("bool", TYPE_SMALLINT);
this->abstractTypeMap.data()->insert("short", TYPE_SMALLINT);
this->abstractTypeMap.data()->insert("int", TYPE_INTEGER);
this->abstractTypeMap.data()->insert("long", TYPE_INTEGER);
this->abstractTypeMap.data()->insert("long long", TYPE_INTEGER);
this->abstractTypeMap.data()->insert("qlonglong", TYPE_INTEGER);
this->abstractTypeMap.data()->insert("float", TYPE_FLOAT);
this->abstractTypeMap.data()->insert("double", TYPE_FLOAT);
this->abstractTypeMap.data()->insert("long double", TYPE_FLOAT);
this->abstractTypeMap.data()->insert("qint", TYPE_INTEGER);
this->abstractTypeMap.data()->insert("quint", TYPE_INTEGER);
this->abstractTypeMap.data()->insert("quuid", TYPE_INTEGER);
this->abstractTypeMap.data()->insert("qfloat", TYPE_FLOAT);
this->abstractTypeMap.data()->insert("unsigned short", TYPE_SMALLINT);
this->abstractTypeMap.data()->insert("unsigned int", TYPE_INTEGER);
this->abstractTypeMap.data()->insert("unsigned long", TYPE_INTEGER);
this->abstractTypeMap.data()->insert("unsigned long long", TYPE_INTEGER);
this->abstractTypeMap.data()->insert("char", TYPE_CHAR);
this->abstractTypeMap.data()->insert("std::string", TYPE_TEXT);
this->abstractTypeMap.data()->insert("std::wstring", TYPE_TEXT);
this->abstractTypeMap.data()->insert("QString", TYPE_TEXT);
this->abstractTypeMap.data()->insert("QVariant", TYPE_TEXT);
this->abstractTypeMap.data()->insert("QUuid", TYPE_TEXT);
this->abstractTypeMap.data()->insert("QDate", TYPE_DATE);
this->abstractTypeMap.data()->insert("QTime", TYPE_TIME);
this->abstractTypeMap.data()->insert("QDateTime", TYPE_DATETIME);
this->abstractTypeMap.data()->insert("QByteArray", TYPE_BINARY);
this->abstractTypeMap.data()->insert("QBitArray", TYPE_BINARY);
this->abstractTypeMap->insert("bool", TYPE_SMALLINT);
this->abstractTypeMap->insert("short", TYPE_SMALLINT);
this->abstractTypeMap->insert("int", TYPE_INTEGER);
this->abstractTypeMap->insert("long", TYPE_INTEGER);
this->abstractTypeMap->insert("long long", TYPE_INTEGER);
this->abstractTypeMap->insert("qlonglong", TYPE_INTEGER);
this->abstractTypeMap->insert("float", TYPE_FLOAT);
this->abstractTypeMap->insert("double", TYPE_FLOAT);
this->abstractTypeMap->insert("long double", TYPE_FLOAT);
this->abstractTypeMap->insert("qint", TYPE_INTEGER);
this->abstractTypeMap->insert("quint", TYPE_INTEGER);
this->abstractTypeMap->insert("quuid", TYPE_INTEGER);
this->abstractTypeMap->insert("qfloat", TYPE_FLOAT);
this->abstractTypeMap->insert("unsigned short", TYPE_SMALLINT);
this->abstractTypeMap->insert("unsigned int", TYPE_INTEGER);
this->abstractTypeMap->insert("unsigned long", TYPE_INTEGER);
this->abstractTypeMap->insert("unsigned long long", TYPE_INTEGER);
this->abstractTypeMap->insert("char", TYPE_CHAR);
this->abstractTypeMap->insert("std::string", TYPE_TEXT);
this->abstractTypeMap->insert("std::wstring", TYPE_TEXT);
this->abstractTypeMap->insert("QString", TYPE_TEXT);
this->abstractTypeMap->insert("QVariant", TYPE_TEXT);
this->abstractTypeMap->insert("QUuid", TYPE_TEXT);
this->abstractTypeMap->insert("QDate", TYPE_DATE);
this->abstractTypeMap->insert("QTime", TYPE_TIME);
this->abstractTypeMap->insert("QDateTime", TYPE_DATETIME);
this->abstractTypeMap->insert("QByteArray", TYPE_BINARY);
this->abstractTypeMap->insert("QBitArray", TYPE_BINARY);
}
QString Schema::quoteSimpleTableName(QString name) {
......
}
QStringList Schema::getTableNames(QString schema) {
return this->database.data()->getDatabase().tables();
Q_UNUSED(schema)
return this->database->getDatabase().tables();
}
QVariant Schema::getLastInsertID() {
QSqlQuery q(this->database.data()->getDatabase());
QSqlQuery q(this->database->getDatabase());
auto lastId = q.lastInsertId();
return lastId;
}
......
bool Schema::containsTable(QString tblname) {
if (this->tables.size() !=
this->database.data()->getDatabase().tables().size()) {
this->database->getDatabase().tables().size()) {
this->setTables(this->getTableSchemas());
}
return this->database.data()->getDatabase().tables().contains(tblname);
return this->database->getDatabase().tables().contains(tblname);
}
QSharedPointer<TableSchema> Schema::getTableSchema(QString name, bool refresh) {
src/schema/sqlitequerybuilder.cpp
QString CuteEntityManager::SqliteQueryBuilder::truncateTable(
QString tableName) const {
return "DELETE FROM " + this->schema.data()->quoteTableName(tableName);
return "DELETE FROM " + this->schema->quoteTableName(tableName);
}
QString CuteEntityManager::SqliteQueryBuilder::dropIndex(QString name,
QString tableName) const {
Q_UNUSED(tableName)
return "DROP INDEX " + this->schema.data()->quoteTableName(name);
return "DROP INDEX " + this->schema->quoteTableName(name);
}
QString CuteEntityManager::SqliteQueryBuilder::dropColumn(QString tableName,
src/schema/sqliteschema.cpp
}
QSharedPointer<QHash<QString, QString>> SqliteSchema::getTypeMap() {
if (this->typeMap.data()->empty()) {
this->typeMap.data()->insert(TYPE_PK,
if (this->typeMap->empty()) {
this->typeMap->insert(TYPE_PK,
"integer PRIMARY KEY AUTOINCREMENT NOT NULL");
this->typeMap.data()->insert(TYPE_BIGPK,
this->typeMap->insert(TYPE_BIGPK,
"integer PRIMARY KEY AUTOINCREMENT NOT NULL");
this->typeMap.data()->insert(TYPE_BOOLEAN, "boolean");
this->typeMap.data()->insert(TYPE_SMALLINT, "smallint");
this->typeMap.data()->insert(TYPE_INTEGER, "integer");
this->typeMap.data()->insert(TYPE_BIGINT, "bigint");
this->typeMap.data()->insert(TYPE_FLOAT, "float");
this->typeMap.data()->insert(TYPE_DOUBLE, "double");
this->typeMap.data()->insert(TYPE_FLOAT, "real");
this->typeMap.data()->insert(TYPE_DECIMAL, "decimal(10,0)");
this->typeMap.data()->insert(TYPE_TEXT, "text");
this->typeMap.data()->insert(TYPE_STRING, "text");
this->typeMap.data()->insert(TYPE_CHAR, "char");
this->typeMap.data()->insert(TYPE_BINARY, "blob");
this->typeMap.data()->insert(TYPE_DATETIME, "datetime");
this->typeMap.data()->insert(TYPE_DATE, "date");
this->typeMap.data()->insert(TYPE_TIME, "time");
this->typeMap.data()->insert(TYPE_TIMESTAMP, "timestamp");
this->typeMap.data()->insert(TYPE_MONEY, "decimal(19,4)");
this->typeMap->insert(TYPE_BOOLEAN, "boolean");
this->typeMap->insert(TYPE_SMALLINT, "smallint");
this->typeMap->insert(TYPE_INTEGER, "integer");
this->typeMap->insert(TYPE_BIGINT, "bigint");
this->typeMap->insert(TYPE_FLOAT, "float");
this->typeMap->insert(TYPE_DOUBLE, "double");
this->typeMap->insert(TYPE_FLOAT, "real");
this->typeMap->insert(TYPE_DECIMAL, "decimal(10,0)");
this->typeMap->insert(TYPE_TEXT, "text");
this->typeMap->insert(TYPE_STRING, "text");
this->typeMap->insert(TYPE_CHAR, "char");
this->typeMap->insert(TYPE_BINARY, "blob");
this->typeMap->insert(TYPE_DATETIME, "datetime");
this->typeMap->insert(TYPE_DATE, "date");
this->typeMap->insert(TYPE_TIME, "time");
this->typeMap->insert(TYPE_TIMESTAMP, "timestamp");
this->typeMap->insert(TYPE_MONEY, "decimal(19,4)");
}
return this->typeMap;
}
......
auto l = QStringList();
QString sql =
"SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence' ORDER BY tbl_name";
auto q = this->database.data()->getQuery();
auto q = this->database->getQuery();
q.prepare(sql);
this->database.data()->select(q);
this->database->select(q);
while (q.next()) {
l.append(q.value(0).toString());
}
......
const QSharedPointer<TableSchema>
&table) {
QHash<QString, QStringList> uniqueIndexes = QHash<QString, QStringList>();
QSqlQuery q = this->database.data()->getQuery();
QSqlQuery q = this->database->getQuery();
q.setForwardOnly(true);
q.exec("PRAGMA index_list(" + this->quoteSimpleTableName(
table->getName()) + ')');
while (q.next()) {
QString indexName = q.value("name").toString();
QSqlQuery q2 = this->database.data()->getQuery();
QSqlQuery q2 = this->database->getQuery();
q2.setForwardOnly(true);
if (q.value("unique").toBool()) {
q2.exec("PRAGMA index_info(" + this->quoteSimpleTableName(indexName) + ")");
......
}
void SqliteSchema::findConstraints(const QSharedPointer<TableSchema> &ts) {
QSqlQuery q = this->database.data()->getQuery();
QSqlQuery q = this->database->getQuery();
q.setForwardOnly(true);
q.exec("PRAGMA foreign_key_list(" + this->quoteSimpleTableName(
ts.data()->getName()) + ')');
auto foreignKeys = ts.data()->getRelations();
ts->getName()) + ')');
auto foreignKeys = ts->getRelations();
while (q.next()) {
bool ok;
int id = q.value("id").toInt(&ok);
......
foreignKeys.insert(QString::number(id), ptr);
}
}
ts.data()->setRelations(foreignKeys);
ts->setRelations(foreignKeys);
}
bool SqliteSchema::findColumns(const QSharedPointer<TableSchema> &ts) {
QSqlQuery q = this->database.data()->getQuery();
QSqlQuery q = this->database->getQuery();
q.setForwardOnly(true);
q.exec("SELECT * FROM " + this->quoteSimpleTableName(ts.data()->getName()) +
q.exec("SELECT * FROM " + this->quoteSimpleTableName(ts->getName()) +
" LIMIT 0");
QHash<QString, QSharedPointer<QSqlField>> columns =
QHash<QString, QSharedPointer<QSqlField>>();
......
QSqlField f = rec.field(var);
columns.insert(f.name(), QSharedPointer<QSqlField>(new QSqlField(f)));
}
ts.data()->setColumns(columns);
ts->setColumns(columns);
return true;
}
QSharedPointer<TableSchema> SqliteSchema::loadTableSchema(QString name) {
auto table = new TableSchema();
auto ptr = QSharedPointer<TableSchema>(table);
table->setName(name);
table->setFullName(name);
auto ptr = QSharedPointer<TableSchema>(new TableSchema());
ptr->setName(name);
ptr->setFullName(name);
if (this->findColumns(ptr)) {
this->findConstraints(ptr);
} else {
src/tableschema.cpp
const QSharedPointer<QSqlField> TableSchema::getColumn(QString name) const {
auto columns = this->getColumns();
foreach (auto schema, columns) {
if (schema.data()->name() == name) {
if (schema->name() == name) {
return schema;
}
}
......
QStringList l;
auto columns = this->getColumns();
foreach (auto schema, columns) {
l.append(schema.data()->name());
l.append(schema->name());
}
return l;
}

Auch abrufbar als: Unified diff