Projekt

Allgemein

Profil

Herunterladen als
Herunterladen (45,7 KB) Statistiken
| Zweig: | Revision:
c22391b2 Christian Ehringfeld
/*
* Copyright (C) 2015 Christian Ehringfeld <c.ehringfeld@t-online.de>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
14f9beed Christian Ehringfeld
#include "querybuilder.h"
b0bf458e Christian Ehringfeld
#include "database.h"
#include <QMetaObject>
#include "entity.h"
a47954c0 Christian Ehringfeld
#include <QRegularExpression>
d568923d Christian Ehringfeld
#include "entityinstancefactory.h"
e8d1537c Christian Ehringfeld
#include "entityhelper.h"
a47954c0 Christian Ehringfeld
b0bf458e Christian Ehringfeld
using namespace CuteEntityManager;
14f9beed Christian Ehringfeld
e0e1ead8 Christian Ehringfeld
QueryBuilder::QueryBuilder(QSharedPointer<Schema> schema,
QSharedPointer<Database> database) {
b0bf458e Christian Ehringfeld
this->schema = schema;
this->database = database;
14f9beed Christian Ehringfeld
}

24425325 Christian Ehringfeld
QueryBuilder::~QueryBuilder() {
}

b7446f4c Christian Ehringfeld
bool QueryBuilder::createTable(const QSharedPointer<Entity> &entity,
bool createRelationTables) const {
b0bf458e Christian Ehringfeld
bool rc = false;
da565582 Christian Ehringfeld
if (entity) {
2e43da3f Christian Ehringfeld
auto tableDefinition = this->generateTableDefinition(entity);
abb9e8c5 Christian Ehringfeld
QString tableName = entity->getTablename();
this->schema->containsTable(tableName) ? rc = true : rc = false;
ce6994c4 Christian Ehringfeld
if (!rc) {
abb9e8c5 Christian Ehringfeld
QSqlQuery q = this->database->getQuery(this->createTable(tableName,
5d93390e Christian Ehringfeld
tableDefinition));
94bf67c7 Christian Ehringfeld
if (this->database->exec(q)) {
b7446f4c Christian Ehringfeld
if (createRelationTables) {
e86c23a2 Christian Ehringfeld
auto relTables = this->generateRelationTables(entity);
auto i = relTables.constBegin();
b7446f4c Christian Ehringfeld
while (i != relTables.constEnd()) {
abb9e8c5 Christian Ehringfeld
auto query = this->database->getQuery(this->createTable(i.key(),
5d93390e Christian Ehringfeld
i.value()));
abb9e8c5 Christian Ehringfeld
this->database->exec(query);
e86c23a2 Christian Ehringfeld
++i;
}
}
abb9e8c5 Christian Ehringfeld
this->schema->getTableSchema(tableName);
ce6994c4 Christian Ehringfeld
rc = true;
if (rc) {
rc = this->createIndices(entity);
}
2e43da3f Christian Ehringfeld
}
b0bf458e Christian Ehringfeld
}
}
return rc;
2e43da3f Christian Ehringfeld
}

bool QueryBuilder::createIndices(const QSharedPointer<Entity> &entity) const {
bool ok = true;
QStringList queries = QStringList();
abb9e8c5 Christian Ehringfeld
QString superIndex = this->createFkSuperClass(entity.data());
ce6994c4 Christian Ehringfeld
if (!superIndex.isEmpty()) {
2e43da3f Christian Ehringfeld
queries.append(superIndex);
}
47f9301a Christian Ehringfeld
queries.append(this->relationFks(entity));
abb9e8c5 Christian Ehringfeld
ok = this->database->transaction(queries);
2e43da3f Christian Ehringfeld
return ok;
}

dd45fcf5 Christian Ehringfeld
47f9301a Christian Ehringfeld
QStringList QueryBuilder::relationFks(const QSharedPointer<Entity> &entity)
const {
dd45fcf5 Christian Ehringfeld
QStringList queries = QStringList();
b0e92bc6 Christian Ehringfeld
if (this->supportsForeignKeys()) {
e8d1537c Christian Ehringfeld
auto relations = EntityHelper::getNonInheritedRelations(entity.data());
auto props = EntityHelper::getMetaProperties(entity.data());
b0e92bc6 Christian Ehringfeld
auto iterator = relations.constBegin();
while (iterator != relations.constEnd()) {
auto relation = iterator.value();
if (relation.getMappedBy().isEmpty() && !relation.getCascadeType().isEmpty()) {
da565582 Christian Ehringfeld
QString update = relation.getCascadeType().contains(CascadeType::MERGE)
5d93390e Christian Ehringfeld
|| relation.getCascadeType().contains(CascadeType::ALL) ?
this->getForeignKeyCascade(
CASCADE) : this->getForeignKeyCascade(NO_ACTION);
da565582 Christian Ehringfeld
QString remove = relation.getCascadeType().contains(CascadeType::REMOVE)
5d93390e Christian Ehringfeld
|| relation.getCascadeType().contains(CascadeType::ALL) ?
this->getForeignKeyCascade(
CASCADE) : this->getForeignKeyCascade(DbForeignKeyCascade::SET_NULL);
b0e92bc6 Christian Ehringfeld
this->createRelationFK(queries, entity, relation,
props.value(relation.getPropertyName()), update, remove);
}
++iterator;
ce6994c4 Christian Ehringfeld
}
dd45fcf5 Christian Ehringfeld
}
return queries;
}

b0e92bc6 Christian Ehringfeld
bool QueryBuilder::supportsForeignKeys() const {
return true;
}

47f9301a Christian Ehringfeld
void QueryBuilder::createRelationFK(QStringList &queries,
const QSharedPointer<Entity> &entity, const Relation &relation,
const QMetaProperty &metaProperty, const QString &update,
const QString &remove) const {
35cf13b7 Christian Ehringfeld
auto ptr = QSharedPointer<Entity>
5d93390e Christian Ehringfeld
(EntityInstanceFactory::createInstance(metaProperty.type()));
abb9e8c5 Christian Ehringfeld
if (ptr) {
da565582 Christian Ehringfeld
if (relation.getType() == RelationType::ONE_TO_ONE
|| relation.getType() == RelationType::MANY_TO_ONE) {
47f9301a Christian Ehringfeld
QString indexName = this->generateIndexName(relation.getPropertyName(),
5d93390e Christian Ehringfeld
entity->getTablename(),
this->generateColumnNameID(relation.getPropertyName()),
ptr->getTablename(), true);
abb9e8c5 Christian Ehringfeld
queries.append(this->addForeignKey(indexName, entity->getTablename(),
47f9301a Christian Ehringfeld
QStringList(this->generateColumnNameID(relation.getPropertyName())),
abb9e8c5 Christian Ehringfeld
ptr->getTablename(),
QStringList(ptr->getPrimaryKey()), remove, update));
47f9301a Christian Ehringfeld
da565582 Christian Ehringfeld
} else if (relation.getType() == RelationType::MANY_TO_MANY) {
f9cef58f Christian Ehringfeld
QString tableName = this->generateManyToManyTableName(entity, ptr, relation);
47f9301a Christian Ehringfeld
queries.append(this->createForeignKeyManyToMany(tableName, entity, update,
5d93390e Christian Ehringfeld
remove));
47f9301a Christian Ehringfeld
queries.append(this->createForeignKeyManyToMany(tableName, ptr, update,
5d93390e Christian Ehringfeld
remove));
47f9301a Christian Ehringfeld
}
}
}

QString QueryBuilder::createForeignKeyManyToMany(const QString &tableName,
5d93390e Christian Ehringfeld
const QSharedPointer<Entity> &entity, const QString &update,
const QString &remove) const {
47f9301a Christian Ehringfeld
QString fkColumn = this->generateManyToManyColumnName(entity);
QString indexName = this->generateIndexName(fkColumn,
5d93390e Christian Ehringfeld
tableName, fkColumn,
entity->getTablename(), true);
47f9301a Christian Ehringfeld
return this->addForeignKey(indexName, tableName, QStringList(fkColumn),
abb9e8c5 Christian Ehringfeld
entity->getTablename(), QStringList(entity->getPrimaryKey()),
47f9301a Christian Ehringfeld
remove, update);
}

ce6994c4 Christian Ehringfeld
QString QueryBuilder::createTable(const QString &tableName,
const QHash<QString, QString> &tableDefinition) const {
2e43da3f Christian Ehringfeld
return this->createTableQuery(tableName,
ce6994c4 Christian Ehringfeld
tableDefinition);
2e43da3f Christian Ehringfeld
}

ce6994c4 Christian Ehringfeld
QString QueryBuilder::createFkSuperClass(const Entity *e) const {
2e43da3f Christian Ehringfeld
QString r = "";
auto superMetaObject = e->metaObject()->superClass();
da565582 Christian Ehringfeld
if (e->getInheritanceStrategy() == InheritanceStrategy::JOINED_TABLE
6d91d381 Christian Ehringfeld
&& QString(superMetaObject->className()) !=
35cf13b7 Christian Ehringfeld
this->entityClassname()) {
ce6994c4 Christian Ehringfeld
Entity *superClass = EntityInstanceFactory::createInstance(
5d93390e Christian Ehringfeld
superMetaObject->className());
ce6994c4 Christian Ehringfeld
if (superClass) {
QString refColumn = superClass->getPrimaryKey();
QString refTable = superClass->getTablename();
r = this->addForeignKey(this->generateIndexName(e->getPrimaryKey(),
5d93390e Christian Ehringfeld
e->getTablename(), refColumn, refTable, true), e->getTablename(),
f62afb13 Christian Ehringfeld
QStringList(e->getPrimaryKey()), refTable, QStringList(refColumn),
this->getForeignKeyCascade(CASCADE),
ce6994c4 Christian Ehringfeld
this->getForeignKeyCascade(CASCADE));
delete superClass;
2e43da3f Christian Ehringfeld
}
}
return r;
b0bf458e Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::createTableQuery(const QString &tableName,
const QHash<QString, QString> &tableDefinition) const {
b0bf458e Christian Ehringfeld
bool first = true;
QString s = "CREATE TABLE ";
3fd96253 Christian Ehringfeld
s.append(this->schema->quoteTableName(tableName).append(" ("));
f4e3904b Christian Ehringfeld
auto i = tableDefinition.constBegin();
b0bf458e Christian Ehringfeld
while (i != tableDefinition.constEnd()) {
if (first) {
first = false;
} else {
9c2f773f Christian Ehringfeld
s.append(", ");
b0bf458e Christian Ehringfeld
}
abb9e8c5 Christian Ehringfeld
s.append(this->schema->quoteColumnName(i.key())).append(" " +
5d93390e Christian Ehringfeld
this->getColumnType(
i.value()));
b0bf458e Christian Ehringfeld
++i;
}
3fd96253 Christian Ehringfeld
s.append(");");
b0bf458e Christian Ehringfeld
return s;
}

d99101ae Christian Ehringfeld
QString QueryBuilder::renameTable(QString tableName, QString newName) const {
abb9e8c5 Christian Ehringfeld
return "RENAME TABLE " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + " TO " +
this->schema->quoteTableName(
newName);
24425325 Christian Ehringfeld
}

d99101ae Christian Ehringfeld
QString QueryBuilder::dropTable(QString tableName) const {
abb9e8c5 Christian Ehringfeld
return "DROP TABLE " + this->schema->quoteTableName(tableName);
24425325 Christian Ehringfeld
}

d99101ae Christian Ehringfeld
QString QueryBuilder::truncateTable(QString tableName) const {
abb9e8c5 Christian Ehringfeld
return "TRUNCATE TABLE " + this->schema->quoteTableName(tableName);
24425325 Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::addColumn(QString tableName, QString columnName,
QString columnType) const {
abb9e8c5 Christian Ehringfeld
return "ALTER TABLE " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + " ADD " +
this->schema->quoteColumnName(
columnName) + " " + this->getColumnType(columnType);
24425325 Christian Ehringfeld
}

QString QueryBuilder::dropColumn(QString tableName, QString columName) const {
abb9e8c5 Christian Ehringfeld
return "ALTER TABLE " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + " DROP COLUMN " +
this->schema->quoteColumnName(columName);
24425325 Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::renameColumn(QString tableName, QString oldName,
QString newName) const {
abb9e8c5 Christian Ehringfeld
return "ALTER TABLE " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + " RENAME COLUMN " +
this->schema->quoteColumnName(oldName) + " TO " +
this->schema->quoteColumnName(
newName);
24425325 Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::alterColumn(QString tableName, QString columnName,
QString newType) const {
abb9e8c5 Christian Ehringfeld
return "ALTER TABLE " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + " CHANGE " +
this->schema->quoteColumnName(columnName) + " " +
this->schema->quoteColumnName(columnName) + this->getColumnType(newType);
24425325 Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::addPrimaryKey(QString name, QString tableName,
QStringList columns) const {
abb9e8c5 Christian Ehringfeld
return "ALTER TABLE " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + " ADD CONSTRAINT " +
this->schema->quoteColumnName(name) + "PRIMARY KEY (" +
this->buildColumns(columns) + " )";
24425325 Christian Ehringfeld
}

QString QueryBuilder::dropPrimaryKey(QString name, QString tableName) const {
abb9e8c5 Christian Ehringfeld
return "ALTER TABLE " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + " DROP CONSTRAINT " +
this->schema->quoteColumnName(name);
24425325 Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::addForeignKey(QString name, QString tableName,
QStringList columns,
QString refTableName,
QStringList refColumns, QString deleteConstraint,
QString updateConstraint) const {
abb9e8c5 Christian Ehringfeld
QString r = "ALTER TABLE " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + "ADD CONSTRAINT " +
this->schema->quoteColumnName(name)
+ " FOREIGN KEY (" + this->buildColumns(columns) + ")" + " REFERENCES " +
this->schema->quoteTableName(
refTableName) +
" (" + this->buildColumns(refColumns) + ")";
d99101ae Christian Ehringfeld
if (!deleteConstraint.isEmpty()) {
r.append(" ON DELETE " + deleteConstraint);
}
if (!updateConstraint.isEmpty()) {
r.append(" ON UPDATE " + updateConstraint);
}
return r;
24425325 Christian Ehringfeld
}

2e43da3f Christian Ehringfeld
QString QueryBuilder::generateIndexName(const QString &name,
const QString &table, const QString &refColumn, const QString &refTable,
const bool fk) const {
return QString(fk ? "fk" : "idx").append("_").append(name).append(table).append(
5d93390e Christian Ehringfeld
refColumn).append(refTable);
f62afb13 Christian Ehringfeld
}

47f9301a Christian Ehringfeld
QString QueryBuilder::generateColumnNameID(QString name) const {
f62afb13 Christian Ehringfeld
return name.append("_id");
2e43da3f Christian Ehringfeld
}

ce6994c4 Christian Ehringfeld
QString QueryBuilder::getForeignKeyCascade(DbForeignKeyCascade cascade) const {
47f9301a Christian Ehringfeld
QString r = "";
ce6994c4 Christian Ehringfeld
switch (cascade) {
case RESTRICT:
47f9301a Christian Ehringfeld
r = "RESTRICT";
ce6994c4 Christian Ehringfeld
break;
case CASCADE:
47f9301a Christian Ehringfeld
r = "CASCADE";
ce6994c4 Christian Ehringfeld
break;
case NO_ACTION:
47f9301a Christian Ehringfeld
r = "NO ACTION";
ce6994c4 Christian Ehringfeld
break;
case SET_DEFAULT:
47f9301a Christian Ehringfeld
r = "SET DEFAULT";
ce6994c4 Christian Ehringfeld
break;
case SET_NULL:
47f9301a Christian Ehringfeld
r = "SET NULL";
ce6994c4 Christian Ehringfeld
break;
}
47f9301a Christian Ehringfeld
return r;
ce6994c4 Christian Ehringfeld
}

24425325 Christian Ehringfeld
QString QueryBuilder::dropForeignKey(QString name, QString tableName) const {
abb9e8c5 Christian Ehringfeld
return "ALTER TABLE " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + " DROP CONSTRAINT " +
this->schema->quoteColumnName(name);
24425325 Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::createIndex(QString name, QString tableName,
QStringList columns,
bool unique) const {
QString s = (unique ? "CREATE UNIQUE INDEX " : "CREATE INDEX ") +
5d93390e Christian Ehringfeld
this->schema->quoteTableName(
name) + " ON " + this->schema->quoteTableName(tableName) + " (";
d99101ae Christian Ehringfeld
s.append(this->buildColumns(columns));
s.append(");");
return s;
24425325 Christian Ehringfeld
}

QString QueryBuilder::dropIndex(QString name, QString tableName) const {
abb9e8c5 Christian Ehringfeld
return "DROP INDEX " + this->schema->quoteTableName(name) + " ON " +
5d93390e Christian Ehringfeld
this->schema->quoteTableName(
tableName);
24425325 Christian Ehringfeld
}

b0bf458e Christian Ehringfeld
QSharedPointer<Database> QueryBuilder::getDatabase() const {
35cf13b7 Christian Ehringfeld
return this->database;
b0bf458e Christian Ehringfeld
}
14f9beed Christian Ehringfeld
b0bf458e Christian Ehringfeld
void QueryBuilder::setDatabase(const QSharedPointer<Database> &value) {
database = value;
14f9beed Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::buildCreateQuery(QHash<QString, QVariant>::const_iterator
i,
dc6b13b4 Christian Ehringfeld
QHash<QString, QVariant>::const_iterator end,
QString &p1, QString &p2) const {
bool first = true;
while (i != end) {
if (!first) {
p1 += ",";
p2 += ",";
} else {
first = false;
}
abb9e8c5 Christian Ehringfeld
p1 += this->schema->quoteColumnName(i.key());
94bf67c7 Christian Ehringfeld
p2 += this->placeHolder(i.key());
dc6b13b4 Christian Ehringfeld
++i;
}
p1 += ")";
p2 += ");";
return p1 + p2;
}

e0e1ead8 Christian Ehringfeld
QHash<QString, QString> QueryBuilder::generateTableDefinition(
5d93390e Christian Ehringfeld
const QSharedPointer<Entity> &entity)
e0e1ead8 Christian Ehringfeld
const {
b0bf458e Christian Ehringfeld
auto map = QHash<QString, QString>();
abb9e8c5 Christian Ehringfeld
auto o = entity->metaObject();
auto superMetaObject = entity->metaObject()->superClass();
5d93390e Christian Ehringfeld
auto superMetaObjectPropertyMap = EntityHelper::getSuperMetaProperties(
entity.data());
abb9e8c5 Christian Ehringfeld
QHash<QString, Relation> relations = entity->getRelations();
b0bf458e Christian Ehringfeld
for (int var = 0; var < o->propertyCount(); ++var) {
auto m = o->property(var);
da565582 Christian Ehringfeld
if ((!superMetaObjectPropertyMap.contains(QString(m.name()))
5d93390e Christian Ehringfeld
|| entity->getInheritanceStrategy() == InheritanceStrategy::PER_CLASS_TABLE)
1a3b37ba Christian Ehringfeld
&& m.name() != QString("objectName") && m.isReadable()
abb9e8c5 Christian Ehringfeld
&& !entity->getTransientAttributes().contains(m.name())) {
6dc7d533 Christian Ehringfeld
if (m.isEnumType()) {
abb9e8c5 Christian Ehringfeld
map.insert(m.name(), this->schema->getTypeMap()->value(
this->schema->TYPE_INTEGER));
d99101ae Christian Ehringfeld
} else if (relations.contains(m.name())) {
Relation r = relations.value(m.name());
e0e1ead8 Christian Ehringfeld
if (r.getType() == RelationType::MANY_TO_ONE
|| (r.getType() == RelationType::ONE_TO_ONE
&& r.getMappedBy().isEmpty())) {
47f9301a Christian Ehringfeld
map.insert(this->generateColumnNameID(QString(m.name())),
abb9e8c5 Christian Ehringfeld
this->schema->TYPE_BIGINT);
d99101ae Christian Ehringfeld
}
abb9e8c5 Christian Ehringfeld
} else if (entity->getBLOBColumns().contains(m.name())) {
map.insert(m.name(), this->schema->getTypeMap()->value(
this->schema->TYPE_BINARY));
6dc7d533 Christian Ehringfeld
} else {
e0e1ead8 Christian Ehringfeld
map.insert(m.name(), this->transformAbstractTypeToRealDbType(
this->transformTypeToAbstractDbType(
m.typeName())));
6dc7d533 Christian Ehringfeld
}
b0bf458e Christian Ehringfeld
}
}
da565582 Christian Ehringfeld
if (QString(superMetaObject->className()) ==
35cf13b7 Christian Ehringfeld
this->entityClassname()
da565582 Christian Ehringfeld
|| entity->getInheritanceStrategy() == InheritanceStrategy::PER_CLASS_TABLE) {
abb9e8c5 Christian Ehringfeld
map.insert(entity->getPrimaryKey(), this->schema->TYPE_BIGPK);
da565582 Christian Ehringfeld
} else {
map.insert(entity->getPrimaryKey(), this->schema->TYPE_BIGINT);
6dc7d533 Christian Ehringfeld
}
b0bf458e Christian Ehringfeld
return map;
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::generateManyToManyTableName(const QSharedPointer<Entity>
5d93390e Christian Ehringfeld
&firstEntity,
const QSharedPointer<Entity> &secondEntity, const Relation &r) const {
09b2592d Christian Ehringfeld
if (r.getMappedBy().isEmpty()) {
return firstEntity->getTablename() + "_" + r.getPropertyName();
98b5b08d Christian Ehringfeld
} else {
09b2592d Christian Ehringfeld
return secondEntity->getTablename() + "_" + r.getMappedBy();
98b5b08d Christian Ehringfeld
}
}

e0e1ead8 Christian Ehringfeld
QHash<QString, QHash<QString, QString>> QueryBuilder::generateRelationTables(
const QSharedPointer<Entity> &entity)
ba800d6d Christian Ehringfeld
const {
auto relations = QHash<QString, QHash<QString, QString>>();
abb9e8c5 Christian Ehringfeld
QHash<QString, Relation> m = entity->getRelations();
e8d1537c Christian Ehringfeld
auto props = EntityHelper::getMetaProperties(entity.data());
ba800d6d Christian Ehringfeld
for (auto i = m.begin(); i != m.end(); ++i) {
813205af Christian Ehringfeld
Relation r = i.value();
da565582 Christian Ehringfeld
if (r.getType() == RelationType::MANY_TO_MANY && r.getMappedBy().isEmpty()) {
813205af Christian Ehringfeld
QHash<QString, QString> h = QHash<QString, QString>();
abb9e8c5 Christian Ehringfeld
h.insert(entity->getPrimaryKey(), this->schema->TYPE_BIGPK);
e0e1ead8 Christian Ehringfeld
h.insert(this->generateManyToManyColumnName(entity),
abb9e8c5 Christian Ehringfeld
this->schema->TYPE_BIGINT);
ccef75f0 Christian Ehringfeld
auto meta = props.value(r.getPropertyName());
da3ce9cf Christian Ehringfeld
QSharedPointer<Entity> ptr = QSharedPointer<Entity>
5d93390e Christian Ehringfeld
(EntityInstanceFactory::createInstance(EntityInstanceFactory::extractEntityType(
QMetaType::typeName(meta.userType()))));
706de2e8 Christian Ehringfeld
h.insert(this->generateManyToManyColumnName(ptr),
abb9e8c5 Christian Ehringfeld
this->schema->TYPE_BIGINT);
09b2592d Christian Ehringfeld
relations.insert(this->generateManyToManyTableName(entity, ptr, r), h);
813205af Christian Ehringfeld
}
}
97f9a843 Christian Ehringfeld
return relations;
813205af Christian Ehringfeld
}


6dc7d533 Christian Ehringfeld
QString QueryBuilder::transformTypeToAbstractDbType(QString typeName) const {
7d60c5a2 Christian Ehringfeld
auto m = this->schema->getAbstractTypeMap();
24425325 Christian Ehringfeld
if (m->contains(typeName)) {
return m->value(typeName);
}
813205af Christian Ehringfeld
for (auto i = m->begin(); i != m->end(); ++i) {
24425325 Christian Ehringfeld
if (i.key().contains(typeName)) {
return i.value();
}
}
abb9e8c5 Christian Ehringfeld
return this->schema->TYPE_TEXT;
24425325 Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::transformAbstractTypeToRealDbType(
5d93390e Christian Ehringfeld
QString typeName) const {
abb9e8c5 Christian Ehringfeld
return this->schema->getTypeMap()->value(typeName);
6dc7d533 Christian Ehringfeld
}

a47954c0 Christian Ehringfeld
QString QueryBuilder::getColumnType(const QString &type) const {
d99101ae Christian Ehringfeld
/**
a47954c0 Christian Ehringfeld
* @WARNING
d99101ae Christian Ehringfeld
*/
7d60c5a2 Christian Ehringfeld
auto tMap = this->schema->getTypeMap();
a47954c0 Christian Ehringfeld
if (tMap->contains(type)) {
return this->transformAbstractTypeToRealDbType(type);
}
//cant believe that this could work in Qt
//https://github.com/yiisoft/yii2/blob/master/framework/db/QueryBuilder.php
e0e1ead8 Christian Ehringfeld
QRegularExpression reg = QRegularExpression(
5d93390e Christian Ehringfeld
QRegularExpression::escape("/^(\\w+)\\((.+?)\\)(.*)$/"));
a47954c0 Christian Ehringfeld
reg.optimize();
e0e1ead8 Christian Ehringfeld
QRegularExpressionMatchIterator i = reg.globalMatch(type, 0,
5d93390e Christian Ehringfeld
QRegularExpression::PartialPreferFirstMatch);
a47954c0 Christian Ehringfeld
short s = 0;
bool ok = false;
QString before = "";
while (i.hasNext() && s < 2) {
before = i.next().captured();
if (tMap->contains(before)) {
ok = true;
}
if (ok) {
e0e1ead8 Christian Ehringfeld
return before.replace(QRegularExpression::escape("/\\(.+\\)/"),
"(" + i.next().captured() + ")");
a47954c0 Christian Ehringfeld
}
s++;
}
9c2f773f Christian Ehringfeld
reg = QRegularExpression(QRegularExpression::escape("/^(\\w+)\\s+/"));
i = reg.globalMatch(type, 0, QRegularExpression::PartialPreferFirstMatch);
a47954c0 Christian Ehringfeld
if (i.hasNext()) {
return before.replace(QRegularExpression::escape("/^w+/"), i.next().captured());
}
return type;
d99101ae Christian Ehringfeld
}

dc6b13b4 Christian Ehringfeld
/**
* @brief QueryBuilder::find
* @param id
* @param tableName
* @return
*/
QSqlQuery QueryBuilder::find(const qint64 &id, const QString &tableName) const {
94bf67c7 Christian Ehringfeld
QString pk = "id";
abb9e8c5 Christian Ehringfeld
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
5d93390e Christian Ehringfeld
tableName)) + " WHERE " + this->schema->quoteColumnName(
pk) + " = " + this->placeHolder(pk) + " LIMIT 1;");
94bf67c7 Christian Ehringfeld
this->bindValue(pk, id, q);
dc6b13b4 Christian Ehringfeld
return q;
}

f5087482 Christian Ehringfeld
QString QueryBuilder::selectBase(const QStringList &tables,
const QStringList &columns) const {
QString r = "SELECT ";
if (columns.isEmpty()) {
r.append("*");
} else {
for (int var = 0; var < columns.size(); ++var) {
if (var != 0) {
r.append(" ");
}
abb9e8c5 Christian Ehringfeld
r.append(this->schema->quoteColumnName(columns.at(var)));
f5087482 Christian Ehringfeld
}
}
r.append(" FROM");
for (int var = 0; var < tables.size(); ++var) {
r.append(" ");
abb9e8c5 Christian Ehringfeld
r.append(this->schema->quoteTableName(tables.at(var)));
f5087482 Christian Ehringfeld
}
return r;
}

95b60eb2 Christian Ehringfeld
QSqlQuery QueryBuilder::find(const qint64 &id,
afde9013 Christian Ehringfeld
const QSharedPointer<Entity> &entity, qint64 offset, QString pk) const {
abb9e8c5 Christian Ehringfeld
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
5d93390e Christian Ehringfeld
entity->getTablename())) + this->joinSuperClasses(
entity) + " WHERE " + this->schema->quoteColumnName(entity->getTablename() + "."
+ pk) + "= " + this->placeHolder(pk) + this->limit(1, offset));
94bf67c7 Christian Ehringfeld
this->bindValue(pk, id, q);
f5087482 Christian Ehringfeld
return q;
}

QSqlQuery QueryBuilder::findAll(const QSharedPointer<Entity> &entity,
const qint64 limit, qint64 offset) {
return this->database->getQuery(this->selectBase(QStringList(
5d93390e Christian Ehringfeld
entity->getTablename())) + " " + this->joinSuperClasses(
6d91d381 Christian Ehringfeld
entity) + this->limit(limit, offset) + ";");
f5087482 Christian Ehringfeld
}

dc6b13b4 Christian Ehringfeld
/**
* @brief QueryBuilder::findByAttributes
* @param m
* @param tableName
* @param ignoreID
* @return
*/
e0e1ead8 Christian Ehringfeld
QSqlQuery QueryBuilder::findByAttributes(const QHash<QString, QVariant> &m,
5d93390e Christian Ehringfeld
const QString &tableName,
const bool &ignoreID, const qint64 limit, const qint64 offset) const {
abb9e8c5 Christian Ehringfeld
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
31916fa0 Christian Ehringfeld
tableName)) + this->where(m, this->andKeyword(), ignoreID) + this->limit(limit,
offset));
dc6b13b4 Christian Ehringfeld
this->bindValues(m, q, ignoreID);
return q;
}

e0e1ead8 Christian Ehringfeld
QSqlQuery QueryBuilder::findByAttributes(const QSharedPointer<Entity> &e,
5d93390e Christian Ehringfeld
bool ignoreID,
const qint64 limit,
const qint64 offset) {
86e5c917 Christian Ehringfeld
QHash<QString, QVariant> values = EntityHelper::getEntityAttributes(
5d93390e Christian Ehringfeld
EntityHelper::getMetaProperties(e.data()), e);
abb9e8c5 Christian Ehringfeld
return this->findByAttributes(values, e->getTablename(), ignoreID, limit,
e0e1ead8 Christian Ehringfeld
offset);
dc6b13b4 Christian Ehringfeld
}

QSqlQuery QueryBuilder::findAll(const QString &tableName) const {
f5087482 Christian Ehringfeld
return this->database->getQuery(this->selectBase(QStringList(tableName)) + ";");
dc6b13b4 Christian Ehringfeld
}

95b60eb2 Christian Ehringfeld
QList<QSqlQuery> QueryBuilder::remove(const QSharedPointer<Entity> &entity)
const {
QList<QSqlQuery> queries = QList<QSqlQuery>();
abb9e8c5 Christian Ehringfeld
queries.append(this->remove(entity->getTablename(),
b5d490c7 Christian Ehringfeld
entity->getProperty(entity->getPrimaryKey()).toLongLong()));
da565582 Christian Ehringfeld
if (entity->getInheritanceStrategy() != InheritanceStrategy::PER_CLASS_TABLE
abb9e8c5 Christian Ehringfeld
&& entity->isInheritanceCascaded()) {
5d93390e Christian Ehringfeld
auto classes = EntityHelper::superClasses(entity.data(), true);
da3ce9cf Christian Ehringfeld
for (int var = 0; var < classes.size(); ++var) {
auto item = classes.at(var);
95b60eb2 Christian Ehringfeld
auto instance = EntityInstanceFactory::createInstance(item->className());
if (instance) {
da3ce9cf Christian Ehringfeld
queries.append(this->remove(instance->getTablename(),
b5d490c7 Christian Ehringfeld
entity->getProperty(entity->getPrimaryKey()).toLongLong()));
95b60eb2 Christian Ehringfeld
delete instance;
instance = 0;
}
}
}
return queries;
}


QSqlQuery QueryBuilder::remove(const QString &tableName,
da3ce9cf Christian Ehringfeld
const qint64 &id, const QString &primaryKey) const {
e0e1ead8 Christian Ehringfeld
QSqlQuery q = this->database->getQuery("DELETE FROM " +
abb9e8c5 Christian Ehringfeld
this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + " WHERE " +
94bf67c7 Christian Ehringfeld
this->schema->quoteColumnName(primaryKey) + "=" + this->placeHolder(
5d93390e Christian Ehringfeld
primaryKey) + ";");
94bf67c7 Christian Ehringfeld
this->bindValue(primaryKey, id, q);
dc6b13b4 Christian Ehringfeld
return q;
}

QSqlQuery QueryBuilder::findId(const QSharedPointer<Entity> &entity) const {
86e5c917 Christian Ehringfeld
QHash<QString, QVariant> values = EntityHelper::getEntityAttributes(
5d93390e Christian Ehringfeld
EntityHelper::getMetaProperties(entity.data()),
entity);
abb9e8c5 Christian Ehringfeld
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
5d93390e Christian Ehringfeld
entity->getTablename()),
QStringList(entity->getPrimaryKey())) + this->where(values,
31916fa0 Christian Ehringfeld
this->andKeyword(), true) + " LIMIT 1");
dc6b13b4 Christian Ehringfeld
this->bindValues(values, q);
return q;
}

e0e1ead8 Christian Ehringfeld
QSqlQuery QueryBuilder::count(const QSharedPointer<Entity> &entity,
bool ignoreID) const {
86e5c917 Christian Ehringfeld
QHash<QString, QVariant> values = EntityHelper::getEntityAttributes(
5d93390e Christian Ehringfeld
EntityHelper::getMetaProperties(entity.data()),
entity);
abb9e8c5 Christian Ehringfeld
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
5d93390e Christian Ehringfeld
entity->getTablename()),
QStringList(this->countFunction())) + this->where(
31916fa0 Christian Ehringfeld
values, this->andKeyword(), ignoreID));
dc6b13b4 Christian Ehringfeld
this->bindValues(values, q, ignoreID);
return q;
}

QSqlQuery QueryBuilder::count(const QString &tableName) const {
abb9e8c5 Christian Ehringfeld
QSqlQuery q = this->database->getQuery(this->selectBase(QStringList(
5d93390e Christian Ehringfeld
tableName), QStringList(this->countFunction())) + ";");
dc6b13b4 Christian Ehringfeld
return q;
}

afde9013 Christian Ehringfeld
QList<QSqlQuery> QueryBuilder::merge(const QSharedPointer<Entity> &entity)
const {
0e3a3d7f Christian Ehringfeld
return this->createOrMerge(entity, false);
}


QList<QSqlQuery> QueryBuilder::createOrMerge(const QSharedPointer<Entity>
5d93390e Christian Ehringfeld
&entity, bool insert) const {
df1e56bd Christian Ehringfeld
const QList<ClassAttributes> attrs = this->inheritedAttributes(entity);
afde9013 Christian Ehringfeld
auto queries = QList<QSqlQuery>();
94bf67c7 Christian Ehringfeld
bool first = true;
afde9013 Christian Ehringfeld
for (int var = 0; var < attrs.size(); ++var) {
auto attr = attrs.at(var);
auto attrHash = attr.getAttributes();
0e3a3d7f Christian Ehringfeld
queries.append(insert ? this->insert(attr.getName(), attrHash,
94bf67c7 Christian Ehringfeld
attr.getPk(), !first) : this->update(attr.getName(), attrHash, attr.getPk()));
if (first) {
first = false;
}
afde9013 Christian Ehringfeld
}
return queries;
dc6b13b4 Christian Ehringfeld
}

99140fe9 Christian Ehringfeld
QList<QSqlQuery> QueryBuilder::create(const QSharedPointer<Entity> &entity)
const {
0e3a3d7f Christian Ehringfeld
return this->createOrMerge(entity, true);
da3ce9cf Christian Ehringfeld
}

8306a974 Christian Ehringfeld
QSqlQuery QueryBuilder::removeAll(const QString &tableName) const {
abb9e8c5 Christian Ehringfeld
return this->database->getQuery(this->truncateTable(tableName));
8306a974 Christian Ehringfeld
}

da3ce9cf Christian Ehringfeld
QSqlQuery QueryBuilder::insert(const QString &tableName,
94bf67c7 Christian Ehringfeld
QHash<QString, QVariant> &attributes, const QString &primaryKey,
bool withId) const {
if (!withId) {
attributes.remove(primaryKey);
}
abb9e8c5 Christian Ehringfeld
QSqlQuery q = this->database->getQuery();
QString p1 = "INSERT INTO " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + "(";
dc6b13b4 Christian Ehringfeld
QString p2 = "VALUES(";
da3ce9cf Christian Ehringfeld
if (!attributes.isEmpty()) {
q.prepare(this->buildCreateQuery(attributes.constBegin(), attributes.constEnd(),
dc6b13b4 Christian Ehringfeld
p1, p2));
}
da3ce9cf Christian Ehringfeld
this->bindValues(attributes, q);
dc6b13b4 Christian Ehringfeld
return q;
}

afde9013 Christian Ehringfeld
QSqlQuery QueryBuilder::update(const QString &tableName,
QHash<QString, QVariant> &attributes, const QString &primaryKey) const {
94bf67c7 Christian Ehringfeld
QSqlQuery q = this->database->getQuery("UPDATE " + this->schema->quoteTableName(
31916fa0 Christian Ehringfeld
tableName) + " SET " + this->attributes(attributes) + " " + this->whereKeyword()
+ " " +
94bf67c7 Christian Ehringfeld
this->schema->quoteColumnName(primaryKey) + " = " + this->placeHolder(
5d93390e Christian Ehringfeld
primaryKey) + ";");
afde9013 Christian Ehringfeld
this->bindValues(attributes, q);
return q;
}

da3ce9cf Christian Ehringfeld
e0e1ead8 Christian Ehringfeld
QSqlQuery QueryBuilder::oneToMany(const QString &tableName,
const QString &attribute,
const qint64 &id,
c599658a Christian Ehringfeld
const qint64 &limit) {
706de2e8 Christian Ehringfeld
QHash<QString, QVariant> values = QHash<QString, QVariant>();
values.insert(attribute, id);
c599658a Christian Ehringfeld
return this->findByAttributes(values, tableName, false, limit);
706de2e8 Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QSqlQuery QueryBuilder::manyToMany(const QString &tableName,
const QString &attribute,
2ce163c3 Christian Ehringfeld
const qint64 &id) {
abb9e8c5 Christian Ehringfeld
QSqlQuery q = this->database->getQuery();
2ce163c3 Christian Ehringfeld
QString sql = this->selectBase(QStringList(tableName), QStringList("*"));
94bf67c7 Christian Ehringfeld
QString pk = "id";
31916fa0 Christian Ehringfeld
sql += " " + this->whereKeyword() + " ";
2ce163c3 Christian Ehringfeld
sql += this->schema->quoteColumnName(
5d93390e Christian Ehringfeld
attribute);
94bf67c7 Christian Ehringfeld
sql += " = " + this->placeHolder(pk) + ";";
706de2e8 Christian Ehringfeld
q.prepare(sql);
94bf67c7 Christian Ehringfeld
this->bindValue(pk, id, q);
706de2e8 Christian Ehringfeld
return q;
}

98b5b08d Christian Ehringfeld
QSqlQuery QueryBuilder::manyToManyDelete(const QString &tableName,
5d93390e Christian Ehringfeld
const QString &attribute, const qint64 &id) {
abb9e8c5 Christian Ehringfeld
QSqlQuery q = this->database->getQuery();
94bf67c7 Christian Ehringfeld
QString pkCol = "id";
abb9e8c5 Christian Ehringfeld
QString sql = "DELETE FROM " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + " WHERE " + this->schema->quoteColumnName(
attribute) + "=" + this->placeHolder(pkCol);
98b5b08d Christian Ehringfeld
q.prepare(sql);
94bf67c7 Christian Ehringfeld
this->bindValue(pkCol, id, q);
98b5b08d Christian Ehringfeld
return q;
}

QSqlQuery QueryBuilder::manyToManyInsert(const QString &tableName,
5d93390e Christian Ehringfeld
const QString &col1, const QString &col2) const {
abb9e8c5 Christian Ehringfeld
QSqlQuery q = this->database->getQuery();
QString sql = "INSERT INTO " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
tableName) + "(" + col1 + "," + col2 + ")"
+ "VALUES(?, ?);";
98b5b08d Christian Ehringfeld
q.prepare(sql);
return q;
}
706de2e8 Christian Ehringfeld
1a3b37ba Christian Ehringfeld
QString QueryBuilder::superClassColumnName(const QMetaObject *&superMeta)
const {
return QString(superMeta->className()).toLower();
}

f5087482 Christian Ehringfeld
QString QueryBuilder::joinSuperClasses(const QSharedPointer<Entity> &entity)
const {
5d93390e Christian Ehringfeld
auto classes = EntityHelper::superClasses(entity.data(), true);
f5087482 Christian Ehringfeld
QString joined = "";
Entity *e = 0;
da3ce9cf Christian Ehringfeld
for (int var = 0; var < classes.size(); ++var) {
auto metaObject = classes.at(var);
f5087482 Christian Ehringfeld
e = EntityInstanceFactory::createInstance(metaObject->className());
if (e) {
6d91d381 Christian Ehringfeld
joined.append(" ");
abb9e8c5 Christian Ehringfeld
joined.append(this->leftJoin(e->getTablename(), entity->getTablename(),
e->getPrimaryKey(), entity->getPrimaryKey()));
f5087482 Christian Ehringfeld
}
delete e;
e = 0;
}
return joined;
}

QString QueryBuilder::countFunction(const QString &distinctColumn) const {
31916fa0 Christian Ehringfeld
return QString(this->countKeyword() + "(" + (distinctColumn.isEmpty() ? "*" :
4677e852 Christian Ehringfeld
(this->distinct() +
this->schema->quoteColumnName(distinctColumn))) + ")");
f5087482 Christian Ehringfeld
}

QString QueryBuilder::distinct() const {
return "DISTINCT";
}

31916fa0 Christian Ehringfeld
QString QueryBuilder::notKeyword() const {
return "NOT";
}

QString QueryBuilder::between() const {
return "BETWEEN";
}

QString QueryBuilder::andKeyword() const {
return "AND";
}

QString QueryBuilder::orKeyword() const {
return "OR";
}

QString QueryBuilder::inKeyword() const {
return "IN";
}

QString QueryBuilder::whereKeyword() const {
return "WHERE";
}

QString QueryBuilder::countKeyword() const {
return "COUNT";
}

QString QueryBuilder::inFunction(Query &q, QString column,
ed03d112 Christian Ehringfeld
QList<QVariant> values, bool notOp) {
31916fa0 Christian Ehringfeld
QString condition = "";
if (!values.isEmpty()) {
bool first = true;
ed03d112 Christian Ehringfeld
condition = this->schema->quoteColumnName(column) + " " + this->appendNot(
notOp) + this->inKeyword() +
31916fa0 Christian Ehringfeld
" (";
for (int var = 0; var < values.size(); ++var) {
if (first) {
first = false;
} else {
condition += ", ";
}
QString paramName = column + "_in" + var;
condition += this->placeHolder(paramName);
q.appendParam(paramName, values.at(var));
}
condition += ")";
}
return condition;
}

QString QueryBuilder::between(QString colName, QString valName1,
ed03d112 Christian Ehringfeld
QString valName2, bool notOp) {
31916fa0 Christian Ehringfeld
return "(" + this->schema->quoteColumnName(colName) + " " + this->between() +
" " + this->placeHolder(valName1) + " " + this->andKeyword() + " " +
this->placeHolder(valName2) + ")";
}

ed03d112 Christian Ehringfeld
QString QueryBuilder::appendNot(bool notOp) {
return (notOp ? (this->notKeyword() + " ") : "");
}

35cf13b7 Christian Ehringfeld
QString QueryBuilder::entityClassname() const {
return QString("CuteEntityManager::Entity");
}

c599658a Christian Ehringfeld
QString QueryBuilder::limit(const qint64 &limit, const qint64 &offset) const {
QString s = "";
if (limit > 0) {
s.append(" LIMIT ").append(QString::number(limit));
}
if (offset > 0) {
s.append(" OFFSET ").append(QString::number(offset));
}
return s;
1e213c09 Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::generateManyToManyColumnName(const QSharedPointer<Entity>
5d93390e Christian Ehringfeld
&entity) const {
b7446f4c Christian Ehringfeld
if (entity) {
abb9e8c5 Christian Ehringfeld
return this->generateColumnNameID(entity->getTablename());
b7446f4c Christian Ehringfeld
}
qDebug() << "Entity is empty!";
return "";
706de2e8 Christian Ehringfeld
}

11bbe9a6 Christian Ehringfeld
QSqlQuery QueryBuilder::getQuery() const {
abb9e8c5 Christian Ehringfeld
return this->database->getQuery();
11bbe9a6 Christian Ehringfeld
}

99140fe9 Christian Ehringfeld
e0e1ead8 Christian Ehringfeld
QHash<QString, QVariant> QueryBuilder::saveAttributes(const
5d93390e Christian Ehringfeld
QSharedPointer<Entity> &entity, QHash<QString, QMetaProperty> props,
QHash<QString, Relation> relations) const {
99140fe9 Christian Ehringfeld
if (props.isEmpty()) {
e8d1537c Christian Ehringfeld
props = EntityHelper::getMetaProperties(entity.data());
99140fe9 Christian Ehringfeld
}
86e5c917 Christian Ehringfeld
auto values = EntityHelper::getEntityAttributes(props, entity);
99140fe9 Christian Ehringfeld
auto relValues = this->getManyToOneAttributes(props, entity, relations);
dc6b13b4 Christian Ehringfeld
auto iterator = relValues.constBegin();
while (iterator != relValues.constEnd()) {
values.insert(iterator.key(), iterator.value());
++iterator;
}
return values;
}

99140fe9 Christian Ehringfeld
QHash<QString, QMetaProperty> QueryBuilder::processProperties(
5d93390e Christian Ehringfeld
const QSharedPointer<Entity> &e,
QHash<QString, QMetaProperty> &usedProperties) const {
e8d1537c Christian Ehringfeld
auto properties = EntityHelper::getMetaProperties(e.data());
59bf3900 Christian Ehringfeld
QMutableHashIterator<QString, QMetaProperty> i(properties);
99140fe9 Christian Ehringfeld
while (i.hasNext()) {
59bf3900 Christian Ehringfeld
i.next();
abb9e8c5 Christian Ehringfeld
if (usedProperties.contains(i.key()) && i.key() != e->getPrimaryKey()) {
99140fe9 Christian Ehringfeld
properties.remove(i.key());
} else {
usedProperties.insert(i.key(), i.value());
}
59bf3900 Christian Ehringfeld
99140fe9 Christian Ehringfeld
}
return properties;
}

QHash<QString, Relation> QueryBuilder::processRelations(
5d93390e Christian Ehringfeld
const QSharedPointer<Entity> &e,
QHash<QString, Relation> &usedRelations) const {
abb9e8c5 Christian Ehringfeld
auto relations = e->getRelations();
99140fe9 Christian Ehringfeld
auto i = QMutableHashIterator<QString, Relation>(relations);
while (i.hasNext()) {
59bf3900 Christian Ehringfeld
i.next();
99140fe9 Christian Ehringfeld
if (usedRelations.contains(i.key())) {
relations.remove(i.key());
} else {
usedRelations.insert(i.key(), i.value());
}
}
return relations;
}

8275b945 Christian Ehringfeld
QList<QueryBuilder::ClassAttributes> QueryBuilder::inheritedAttributes(
5d93390e Christian Ehringfeld
const QSharedPointer<Entity> &entity) const {
8275b945 Christian Ehringfeld
auto list = QList<QueryBuilder::ClassAttributes>();
da565582 Christian Ehringfeld
if (entity->getInheritanceStrategy() == InheritanceStrategy::JOINED_TABLE) {
99140fe9 Christian Ehringfeld
auto classes = QList<const QMetaObject *>();
abb9e8c5 Christian Ehringfeld
classes.append(entity->metaObject());
5d93390e Christian Ehringfeld
classes.append(EntityHelper::superClasses(entity.data(), true));
99140fe9 Christian Ehringfeld
auto usedProperties = QHash<QString, QMetaProperty>();
auto usedRelations = QHash<QString, Relation>();
QSharedPointer<Entity> e;
59bf3900 Christian Ehringfeld
for (int var = classes.size() - 1; var >= 0; --var) {
99140fe9 Christian Ehringfeld
auto metaObj = classes.at(var);
e = QSharedPointer<Entity>(EntityInstanceFactory::createInstance(
59bf3900 Christian Ehringfeld
metaObj));
99140fe9 Christian Ehringfeld
if (e) {
abb9e8c5 Christian Ehringfeld
list.append(QueryBuilder::ClassAttributes(e->getTablename(),
5d93390e Christian Ehringfeld
this->saveAttributes(entity, this->processProperties(e, usedProperties),
this->processRelations(e, usedRelations)), e->getPrimaryKey()));
99140fe9 Christian Ehringfeld
} else {
033279c9 SebastianDiel
qDebug() << "Instance of " << metaObj->className() << " could not be created";
99140fe9 Christian Ehringfeld
break;
}
}
} else {
abb9e8c5 Christian Ehringfeld
list.append(QueryBuilder::ClassAttributes(entity->getTablename(),
5d93390e Christian Ehringfeld
this->saveAttributes(entity), entity->getPrimaryKey()));
99140fe9 Christian Ehringfeld
}
return list;
8275b945 Christian Ehringfeld
}

f5087482 Christian Ehringfeld
QString QueryBuilder::leftJoin(const QString &foreignTable,
const QString &tableName, const QString &foreignKey,
const QString &primaryKey) const {
abb9e8c5 Christian Ehringfeld
return "LEFT JOIN " + this->schema->quoteTableName(
5d93390e Christian Ehringfeld
foreignTable) + " ON " +
this->schema->quoteColumnName(foreignTable + "." + primaryKey) + "=" +
this->schema->quoteColumnName(
tableName + "." + foreignKey);
f5087482 Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QHash<QString, QVariant> QueryBuilder::getManyToOneAttributes(
5d93390e Christian Ehringfeld
QHash<QString, QMetaProperty>
props,
const QSharedPointer<Entity> &entity,
QHash<QString, Relation> relations) const {
ba800d6d Christian Ehringfeld
auto map = QHash<QString, QVariant>();
99140fe9 Christian Ehringfeld
if (relations.isEmpty()) {
abb9e8c5 Christian Ehringfeld
relations = entity->getRelations();
99140fe9 Christian Ehringfeld
}
ba800d6d Christian Ehringfeld
auto i = relations.constBegin();
while (i != relations.constEnd()) {
Relation r = i.value();
da565582 Christian Ehringfeld
if ((r.getType() == RelationType::MANY_TO_ONE && props.contains(i.key()))
|| (r.getType() == RelationType::ONE_TO_ONE && r.getMappedBy().isEmpty())) {
abb9e8c5 Christian Ehringfeld
auto v = props.value(i.key()).read(entity.data());
df1e56bd Christian Ehringfeld
QSharedPointer<Entity> e = EntityInstanceFactory::castQVariant(v);
if (e) {
this->insertRelationId(e.data(), map, i.key());
b0bf458e Christian Ehringfeld
}
}
1cee0f5b Christian Ehringfeld
++i;
b0bf458e Christian Ehringfeld
}
return map;
}

e0e1ead8 Christian Ehringfeld
void QueryBuilder::insertRelationId(const Entity *e,
QHash<QString, QVariant> &map,
QString relName) const {
b5d490c7 Christian Ehringfeld
if (e && e->getProperty(e->getPrimaryKey()).toLongLong() > -1) {
da3ce9cf Christian Ehringfeld
map.insert(this->generateColumnNameID(relName),
b5d490c7 Christian Ehringfeld
e->getProperty(e->getPrimaryKey()));
b0bf458e Christian Ehringfeld
}
}

d99101ae Christian Ehringfeld
QString QueryBuilder::buildColumns(const QStringList &columns) const {
QString r = "";
bool first = true;
for (int var = 0; var < columns.size(); ++var) {
if (!first) {
r.append(",");
} else {
first = false;
}
r.append(columns.at(var));
}
return r;
}

e0e1ead8 Christian Ehringfeld
void QueryBuilder::bindValues(const QHash<QString, QVariant> &h, QSqlQuery &q,
da3ce9cf Christian Ehringfeld
bool ignoreID, const QString &primaryKey) const {
dc6b13b4 Christian Ehringfeld
QHash<QString, QVariant>::const_iterator i = h.constBegin();
while (i != h.constEnd()) {
5d93390e Christian Ehringfeld
if ((!ignoreID || (ignoreID && !(i.key() == primaryKey)))
&& !i.value().isNull()) {
94bf67c7 Christian Ehringfeld
this->bindValue(i.key(), i.value(), q);
dc6b13b4 Christian Ehringfeld
}
++i;
}
}

94bf67c7 Christian Ehringfeld
void QueryBuilder::bindValue(const QString &key, const QVariant &value,
QSqlQuery &q) const {
q.bindValue(this->placeHolder(key), value);
}

QString QueryBuilder::placeHolder(const QString &key) const {
return QString(":" + key);
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::where(const QHash<QString, QVariant> &m,
const QString &conjunction,
86e5c917 Christian Ehringfeld
bool ignoreID, const QString &primaryKey, bool withKeyword) const {
da3ce9cf Christian Ehringfeld
if (m.size() == 0 || (ignoreID && m.contains(primaryKey) && m.size() == 1)) {
dc6b13b4 Christian Ehringfeld
return "";
}
86e5c917 Christian Ehringfeld
return (withKeyword ? " WHERE " : "") + this->attributes(m, conjunction, ignoreID, primaryKey);
dc6b13b4 Christian Ehringfeld
}

e0e1ead8 Christian Ehringfeld
QString QueryBuilder::attributes(const QHash<QString, QVariant> &m,
const QString &conjunction,
da3ce9cf Christian Ehringfeld
bool ignoreID, const QString &primaryKey) const {
dc6b13b4 Christian Ehringfeld
QString rc = "";
if (!m.isEmpty()) {
QHash<QString, QVariant>::const_iterator i = m.constBegin();
while (i != m.constEnd()) {
5d93390e Christian Ehringfeld
if ((!ignoreID || (ignoreID && !(i.key() == primaryKey)))
&& !i.value().isNull()) {
dc6b13b4 Christian Ehringfeld
if (!(rc == "")) {
rc += " " + conjunction + " ";
}
94bf67c7 Christian Ehringfeld
rc += this->schema->quoteColumnName(i.key()) + "=" + this->placeHolder(i.key());
dc6b13b4 Christian Ehringfeld
}
++i;
}
}
return rc;
}
ba800d6d Christian Ehringfeld
b0bf458e Christian Ehringfeld
QSharedPointer<Schema> QueryBuilder::getSchema() const {
return schema;
}
14f9beed Christian Ehringfeld
b0bf458e Christian Ehringfeld
void QueryBuilder::setSchema(const QSharedPointer<Schema> &value) {
schema = value;
14f9beed Christian Ehringfeld
}
8275b945 Christian Ehringfeld
99140fe9 Christian Ehringfeld
QueryBuilder::ClassAttributes::ClassAttributes(const QString name,
5d93390e Christian Ehringfeld
const QHash<QString, QVariant> attributes, QString pk) {
99140fe9 Christian Ehringfeld
this->name = name;
this->attributes = attributes;
this->pk = pk;
}

8275b945 Christian Ehringfeld
QString QueryBuilder::ClassAttributes::getName() const {
return name;
}

void QueryBuilder::ClassAttributes::setName(const QString &value) {
name = value;
}

QHash<QString, QVariant> QueryBuilder::ClassAttributes::getAttributes() const {
return attributes;
}

void QueryBuilder::ClassAttributes::setAttributes(const QHash<QString, QVariant>
5d93390e Christian Ehringfeld
&value) {
8275b945 Christian Ehringfeld
attributes = value;
}
99140fe9 Christian Ehringfeld
QString QueryBuilder::ClassAttributes::getPk() const {
return pk;
}

void QueryBuilder::ClassAttributes::setPk(const QString &value) {
pk = value;
}
5d93390e Christian Ehringfeld
void QueryBuilder::andOperator(Query &query,
QHash<QString, QVariant> conditions) {
bool first = true;
QString condition = "";
for (auto var = conditions.constBegin(); var != conditions.constEnd(); ++var) {
if (first) {
first = false;
} else {
31916fa0 Christian Ehringfeld
condition += " " + this->andKeyword() + " ";
5d93390e Christian Ehringfeld
}
condition += this->schema->quoteColumnName(var.key()) + " = " +
this->placeHolder(var.key());
query.appendParam(var.key(), var.value());
}
query.appendCondition(condition);
}

void QueryBuilder::arbitraryOperator(Query &query, QString op, QString column,
QVariant value) {
query.appendCondition(column + " " + op + this->placeHolder(column));
query.appendParam(column, value);
}

void QueryBuilder::plainOr(Query &query) {
31916fa0 Christian Ehringfeld
query.appendCondition(this->orKeyword());
5d93390e Christian Ehringfeld
}

void QueryBuilder::plainAnd(Query &query) {
31916fa0 Christian Ehringfeld
query.appendCondition(this->andKeyword());
5d93390e Christian Ehringfeld
}


ed03d112 Christian Ehringfeld
void QueryBuilder::where(Query &query, QString column, QVariant value) {
QString placeholder = column + "_where";
query.appendCondition(this->schema->quoteColumnName(column) + "=" +
this->placeHolder(placeholder));
query.appendParam(placeholder, value);
5d93390e Christian Ehringfeld
}

void QueryBuilder::where(Query &query, QHash<QString, QVariant> conditions,
QString concat) {
86e5c917 Christian Ehringfeld
QString condition = this->where(conditions,concat,false,"id",false);
for (auto i = conditions.constBegin(); i != conditions.constEnd(); ++i) {
query.appendParam(i.key(),i.value());
}
query.appendCondition(condition);
5d93390e Christian Ehringfeld
}

void QueryBuilder::between(Query &query, QString column, QVariant firstValue,
QVariant secondValue) {
31916fa0 Christian Ehringfeld
QString firstPh = column + "_bet1";
QString secondPh = column + "_bet2";
ed03d112 Christian Ehringfeld
this->appendCondition(query, firstPh, secondPh, firstValue, secondValue,
this->between(column, firstPh, secondPh));
5d93390e Christian Ehringfeld
}

ed03d112 Christian Ehringfeld
void QueryBuilder::notBetween(Query &query, QString column, QVariant firstValue,
QVariant secondValue) {
QString firstPh = column + "_nbet1";
QString secondPh = column + "_nbet2";
this->appendCondition(query, firstPh, secondPh, firstValue, secondValue,
this->between(column, firstPh, secondPh, true));
5d93390e Christian Ehringfeld
}

ed03d112 Christian Ehringfeld
void QueryBuilder::appendCondition(Query &q, QString ph1, QString ph2,
QVariant val1, QVariant val2, QString condition) {
q.appendParam(ph1, val1);
q.appendParam(ph2, val2);
q.appendCondition(condition);
5d93390e Christian Ehringfeld
}

ed03d112 Christian Ehringfeld
void QueryBuilder::in(Query &query, QString column, QList<QVariant> values) {
query.appendCondition(this->inFunction(query, column, values));
}
5d93390e Christian Ehringfeld
ed03d112 Christian Ehringfeld
void QueryBuilder::notIn(Query &query, QString column, QList<QVariant> values) {
query.appendCondition(this->inFunction(query, column,
values, true));
5d93390e Christian Ehringfeld
}

void QueryBuilder::orOperator(Query &query,
ed03d112 Christian Ehringfeld
QHash<QString, QVariant> conditions, bool like) {
if (!conditions.isEmpty()) {
QString condition = "(";
bool first = true;
for (auto i = conditions.constBegin(); i != conditions.constEnd(); ++i) {
if (first) {
first = false;
} else {
condition += " " + this->orKeyword() + " ";
}
condition += this->schema->quoteColumnName(i.key()) + (like ? " LIKE " : "=") +
this->placeHolder(i.key());
query.appendParam(i.key(), i.value());
}
condition += ")";
query.appendCondition(condition);
}
5d93390e Christian Ehringfeld
}

QString QueryBuilder::where(const QSharedPointer<Entity> &entity,
QString conjunction,
bool ignoreID) const {
86e5c917 Christian Ehringfeld
return this->where(EntityHelper::getEntityAttributes(EntityHelper::getMetaProperties(
5d93390e Christian Ehringfeld
entity.data()),
entity),
conjunction, ignoreID, entity->getPrimaryKey());
}