Apply clang-format to Lts/Common and DTC/enum headers

- Formatted all CodeGen module files (9 files)
- Formatted LtsAppDescriptor module files
- Formatted LtsAppManager/AppChooser files
- Applied clang-format to all DTC and enum headers across modules
- Removed coordTransTests from CommonUnitTestsPlaceholder (moved to tests/)

Cosmetic changes only, no functional modifications.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
torstenandCopilot committed 2026-08-19 14:46:29 +02:00
1 parent 1881d68aef
commit d6b6ffce7c
848 files changed
+89305 -100020

No files matched your search

+261 -284
View File
@@ -1,10 +1,11 @@
#include "CppTopicGeneratorGrantlee.h"
#include "StructBuilder.h"
#include <QCryptographicHash>
#include <NGLLogger/INGLLogger.h>
#include <QCryptographicHash>
#include <grantlee/context.h>
#ifdef RTI_HEADER_AVAILABLE
@@ -13,341 +14,317 @@
using namespace CodeGen;
CppTopicGeneratorGrantlee::CppTopicGeneratorGrantlee()
: GeneratorGrantleeBase("CodeGen.CppTopicGeneratorGrantlee")
{}
CppTopicGeneratorGrantlee::CppTopicGeneratorGrantlee() : GeneratorGrantleeBase("CodeGen.CppTopicGeneratorGrantlee") {}
bool CppTopicGeneratorGrantlee::init(const XmlReader *reader, StructBuilder *structBuilder)
bool CppTopicGeneratorGrantlee::init(const XmlReader* reader, StructBuilder* structBuilder)
{
m_reader = reader;
if (!GeneratorGrantleeBase::initInternal(reader, structBuilder))
return false;
m_reader = reader;
if (!GeneratorGrantleeBase::initInternal(reader, structBuilder))
return false;
addCustomFunctions(reader->getCustomFunctions());
addCustomFunctions(reader->getCustomFunctions());
return initDataTopics() && initFunctionTopics() && initIdlStructs();
return initDataTopics() && initFunctionTopics() && initIdlStructs();
}
bool CppTopicGeneratorGrantlee::initDataTopics()
{
DataTopicsWrapper *dataTopicsWrapper = new DataTopicsWrapper(QString(), this);
const auto dataTopics = m_reader->getIdlStructInformation();
QVector<IdlData> keyColumns;
QVector<IdlData> trColumns;
for (const CodeGen::TopicTypeInformation &tti : dataTopics)
{
if (!tti.isDataObject)
continue;
keyColumns.clear();
trColumns.clear();
const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(tti.name);
if (!ctti.isValid())
DataTopicsWrapper* dataTopicsWrapper = new DataTopicsWrapper(QString(), this);
const auto dataTopics = m_reader->getIdlStructInformation();
QVector<IdlData> keyColumns;
QVector<IdlData> trColumns;
for (const CodeGen::TopicTypeInformation& tti : dataTopics)
{
ERROR_LOG(m_logger) << "could not find informations for struct " << tti.name;
continue;
if (!tti.isDataObject)
continue;
keyColumns.clear();
trColumns.clear();
const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(tti.name);
if (!ctti.isValid())
{
ERROR_LOG(m_logger) << "could not find informations for struct " << tti.name;
continue;
}
DataTopicWrapper* dtw = dataTopicsWrapper->addDataTopic(ctti);
getSpecialColumns(ctti, keyColumns, trColumns);
if (keyColumns.size() == 1)
dtw->setKeyColumnData(keyColumns.first());
dtw->setTrColumns(trColumns);
if (ctti.recordTopic)
{
const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name));
if (!cti.isEmpty())
dtw->setRecordTableInformation(cti);
}
else
{
if (ctti.isDataObject)
m_structBuilder->buildJSonStructureInformationFromIdlData(ctti);
}
}
DataTopicWrapper *dtw = dataTopicsWrapper->addDataTopic(ctti);
getSpecialColumns(ctti, keyColumns, trColumns);
if (keyColumns.size() == 1)
dtw->setKeyColumnData(keyColumns.first());
dtw->setTrColumns(trColumns);
if (ctti.recordTopic)
m_ctx->insert(QStringLiteral("dataTopics"), dataTopicsWrapper);
QSet<QString> exportedSubTopics;
DataTopicsWrapper* subTopicsWrapper = new DataTopicsWrapper(QString(), this);
const QVector<QSharedPointer<DataTypeInfo>> serializeTopics = m_structBuilder->getSerializeFromToJsonTopics();
for (const QSharedPointer<DataTypeInfo>& dti : serializeTopics)
{
const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name));
if (!cti.isEmpty())
dtw->setRecordTableInformation(cti);
if (exportedSubTopics.contains(dti->idlType()))
continue;
if (dti->isStructure())
{
const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(dti->idlType());
if (!ctti.isValid())
{
ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType();
continue;
}
const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name));
if (cti.isEmpty())
{
ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType();
continue;
}
DEBUG_LOG(m_logger) << "Adding substruct topic " << ctti.name;
DataTopicWrapper* dtw = subTopicsWrapper->addDataTopic(ctti);
dtw->setRecordTableInformation(cti);
exportedSubTopics += dti->idlType();
}
}
else
m_ctx->insert(QStringLiteral("serializeTopics"), subTopicsWrapper);
QVector<MemberInformationListWrapper*> jsonTopics;
const QMap<QString, QVector<MemberInformation>> jsonExport = m_structBuilder->jsonStructureInformation();
for (auto it = jsonExport.begin(); it != jsonExport.end(); ++it)
{
if (ctti.isDataObject)
m_structBuilder->buildJSonStructureInformationFromIdlData(ctti);
MemberInformationListWrapper* mil = new MemberInformationListWrapper(it.key(), it.value(), this);
jsonTopics += mil;
}
}
m_ctx->insert(QStringLiteral("dataTopics"), dataTopicsWrapper);
m_ctx->insert(QStringLiteral("jsonTopics"), QVariant::fromValue(jsonTopics));
QSet<QString> exportedSubTopics;
DataTopicsWrapper *subTopicsWrapper = new DataTopicsWrapper(QString(), this);
const QVector<QSharedPointer<DataTypeInfo>> serializeTopics = m_structBuilder->getSerializeFromToJsonTopics();
for (const QSharedPointer<DataTypeInfo> &dti : serializeTopics)
{
if (exportedSubTopics.contains(dti->idlType()))
continue;
if (dti->isStructure())
{
const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(dti->idlType());
if (!ctti.isValid())
{
ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType();
continue;
}
const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name));
if (cti.isEmpty())
{
ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType();
continue;
}
DEBUG_LOG(m_logger) << "Adding substruct topic " << ctti.name;
DataTopicWrapper *dtw = subTopicsWrapper->addDataTopic(ctti);
dtw->setRecordTableInformation(cti);
exportedSubTopics += dti->idlType();
}
}
m_ctx->insert(QStringLiteral("serializeTopics"), subTopicsWrapper);
QVector<MemberInformationListWrapper *> jsonTopics;
const QMap<QString, QVector<MemberInformation>> jsonExport = m_structBuilder->jsonStructureInformation();
for (auto it = jsonExport.begin(); it != jsonExport.end(); ++it)
{
MemberInformationListWrapper *mil = new MemberInformationListWrapper(it.key(), it.value(), this);
jsonTopics += mil;
}
m_ctx->insert(QStringLiteral("jsonTopics"), QVariant::fromValue(jsonTopics));
return true;
}
bool CppTopicGeneratorGrantlee::getSpecialColumns(const CompleteTopicTypeInformation &tti,
QVector<IdlData> &keyColumns,
QVector<IdlData> &trColumns) const
{
DEBUG_LOG(m_logger) << "Get special columns for " << tti.name << " - base is " << tti.baseValueType;
if (!tti.isValid())
{
ERROR_LOG(m_logger) << "tti is not valid ...";
return false;
}
for (const IdlData &ci : tti.members)
{
if (ci.isKey)
keyColumns += ci;
if (ci.isTranslatable)
trColumns += ci;
}
if (tti.baseValueType.isEmpty())
return true;
return getSpecialColumns(topicTypeInformationByDerivedTopic(tti), keyColumns, trColumns);
}
bool CppTopicGeneratorGrantlee::getSpecialColumns(const CompleteTopicTypeInformation& tti, QVector<IdlData>& keyColumns,
QVector<IdlData>& trColumns) const
{
DEBUG_LOG(m_logger) << "Get special columns for " << tti.name << " - base is " << tti.baseValueType;
if (!tti.isValid())
{
ERROR_LOG(m_logger) << "tti is not valid ...";
return false;
}
for (const IdlData& ci : tti.members)
{
if (ci.isKey)
keyColumns += ci;
if (ci.isTranslatable)
trColumns += ci;
}
if (tti.baseValueType.isEmpty())
return true;
return getSpecialColumns(topicTypeInformationByDerivedTopic(tti), keyColumns, trColumns);
}
bool CppTopicGeneratorGrantlee::initFunctionTopics()
{
const QVector<FunctionTopic> functionTopics = m_reader->getFunctionTopics();
FunctionTopicsWrapper *functionTopicsWrapper(new FunctionTopicsWrapper(QStringLiteral("functionTopics"), this));
for (const FunctionTopic &ft : functionTopics)
{
if (!handleStruct(ft, functionTopicsWrapper))
return false;
}
m_ctx->insert(QStringLiteral("functionTopics"), functionTopicsWrapper);
return true;
}
bool CppTopicGeneratorGrantlee::handleStruct(const FunctionTopic &ft,
FunctionTopicsWrapper *functionTopicsWrapper)
{
DEBUG_LOG(m_logger) << "handling FunctionTopic: " << ft.name;
const CompleteTopicTypeInformation siRequest = m_structBuilder->topicTypeInformationByStructType(ft.requestTopicType);
if (!siRequest.isValid())
{
WARNING_LOG(m_logger) << "Could not get topic informations about request topic "
<< ft.requestTopicName;
return false;
}
const CompleteTopicTypeInformation siReply = m_structBuilder->topicTypeInformationByStructType(ft.replyTopicType);
if (!siReply.isValid())
{
WARNING_LOG(m_logger) << "Could not get topic informations about reply topic "
<< ft.replyTopicType;
return false;
}
FunctionTopicWrapper *ftw = functionTopicsWrapper->addFunctionTopic(ft, siRequest, siReply);
const QByteArray hash = QCryptographicHash::hash(ft.requestTopicName.toUtf8(), QCryptographicHash::Sha3_512).toHex().left(16);
ftw->setReplyHandlerHash(QStringLiteral("0x") + QString::fromLatin1(hash) + QStringLiteral("LL"));
if (!addRequesterRequestParams(ft.name, siRequest, ftw) ||
!addRequesterReplyParams(ft.name, siReply, ftw))
return false;
return true;
}
bool CppTopicGeneratorGrantlee::addRequesterRequestParams(const QString &request_name,
const CompleteTopicTypeInformation &request,
FunctionTopicWrapper *ftw)
{
if (request.hasBaseValue())
{
const CompleteTopicTypeInformation siBase = m_structBuilder->topicTypeInformationByStructType(request.baseValueType);
if (!siBase.isValid())
const QVector<FunctionTopic> functionTopics = m_reader->getFunctionTopics();
FunctionTopicsWrapper* functionTopicsWrapper(new FunctionTopicsWrapper(QStringLiteral("functionTopics"), this));
for (const FunctionTopic& ft : functionTopics)
{
WARNING_LOG(m_logger) << "Could not get topic informations about base request topic "
<< request.baseValueType;
return false;
if (!handleStruct(ft, functionTopicsWrapper))
return false;
}
if (!addRequesterRequestParams(request_name, siBase, ftw))
return false;
}
ftw->addRequestParams(request.members);
return true;
m_ctx->insert(QStringLiteral("functionTopics"), functionTopicsWrapper);
return true;
}
bool CppTopicGeneratorGrantlee::addRequesterReplyParams(const QString &request_name,
const CompleteTopicTypeInformation &reply,
FunctionTopicWrapper *ftw)
bool CppTopicGeneratorGrantlee::handleStruct(const FunctionTopic& ft, FunctionTopicsWrapper* functionTopicsWrapper)
{
if (reply.hasBaseValue())
{
const CompleteTopicTypeInformation siBase = m_structBuilder->topicTypeInformationByStructType(reply.baseValueType);
if (!siBase.isValid())
DEBUG_LOG(m_logger) << "handling FunctionTopic: " << ft.name;
const CompleteTopicTypeInformation siRequest =
m_structBuilder->topicTypeInformationByStructType(ft.requestTopicType);
if (!siRequest.isValid())
{
WARNING_LOG(m_logger) << "Could not get topic informations about base reply topic "
<< reply.baseValueType;
return false;
WARNING_LOG(m_logger) << "Could not get topic informations about request topic " << ft.requestTopicName;
return false;
}
if (!addRequesterReplyParams(request_name, siBase, ftw))
return false;
}
ftw->addReplyParams(reply.members);
const CompleteTopicTypeInformation siReply = m_structBuilder->topicTypeInformationByStructType(ft.replyTopicType);
if (!siReply.isValid())
{
WARNING_LOG(m_logger) << "Could not get topic informations about reply topic " << ft.replyTopicType;
return false;
}
return true;
FunctionTopicWrapper* ftw = functionTopicsWrapper->addFunctionTopic(ft, siRequest, siReply);
const QByteArray hash =
QCryptographicHash::hash(ft.requestTopicName.toUtf8(), QCryptographicHash::Sha3_512).toHex().left(16);
ftw->setReplyHandlerHash(QStringLiteral("0x") + QString::fromLatin1(hash) + QStringLiteral("LL"));
if (!addRequesterRequestParams(ft.name, siRequest, ftw) || !addRequesterReplyParams(ft.name, siReply, ftw))
return false;
return true;
}
bool CppTopicGeneratorGrantlee::handleIdlStruct(const CompleteTopicTypeInformation &csi,
QSet<QString> &idlStructNames,
QVector<IdlStructWrapper *> &idlStructs)
bool CppTopicGeneratorGrantlee::addRequesterRequestParams(const QString& request_name,
const CompleteTopicTypeInformation& request,
FunctionTopicWrapper* ftw)
{
if (!csi.isValid())
return true;
if (idlStructNames.contains(csi.name))
return true;
if (csi.hasBaseValue())
{
const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(csi.baseValueType, false);
if (ctti.isValid())
if (request.hasBaseValue())
{
const CompleteTopicTypeInformation siBase =
m_structBuilder->topicTypeInformationByStructType(request.baseValueType);
if (!siBase.isValid())
{
WARNING_LOG(m_logger) << "Could not get topic informations about base request topic "
<< request.baseValueType;
return false;
}
if (!addRequesterRequestParams(request_name, siBase, ftw))
return false;
}
ftw->addRequestParams(request.members);
return true;
}
bool CppTopicGeneratorGrantlee::addRequesterReplyParams(const QString& request_name,
const CompleteTopicTypeInformation& reply,
FunctionTopicWrapper* ftw)
{
if (reply.hasBaseValue())
{
const CompleteTopicTypeInformation siBase =
m_structBuilder->topicTypeInformationByStructType(reply.baseValueType);
if (!siBase.isValid())
{
WARNING_LOG(m_logger) << "Could not get topic informations about base reply topic " << reply.baseValueType;
return false;
}
if (!addRequesterReplyParams(request_name, siBase, ftw))
return false;
}
ftw->addReplyParams(reply.members);
return true;
}
bool CppTopicGeneratorGrantlee::handleIdlStruct(const CompleteTopicTypeInformation& csi, QSet<QString>& idlStructNames,
QVector<IdlStructWrapper*>& idlStructs)
{
if (!csi.isValid())
return true;
if (idlStructNames.contains(csi.name))
return true;
if (csi.hasBaseValue())
{
const CompleteTopicTypeInformation ctti =
m_structBuilder->topicTypeInformationByStructType(csi.baseValueType, false);
if (ctti.isValid())
{
#ifdef RTI_HEADER_AVAILABLE
if (ctti.extensibility == dds::core::xtypes::ExtensibilityKind_def::FINAL)
{
ERROR_LOG(m_logger) << "Base struct (" << ctti.name
<< ") has final extensibility - this is not allowed";
return false;
}
if (ctti.extensibility == dds::core::xtypes::ExtensibilityKind_def::FINAL)
{
ERROR_LOG(m_logger) << "Base struct (" << ctti.name
<< ") has final extensibility - this is not allowed";
return false;
}
#else
// RTI not available - skip extensibility check (assume EXTENSIBLE)
Q_UNUSED(ctti.extensibility);
// RTI not available - skip extensibility check (assume EXTENSIBLE)
Q_UNUSED(ctti.extensibility);
#endif
if (!idlStructNames.contains(csi.baseValueType))
{
if (!handleIdlStruct(ctti, idlStructNames, idlStructs))
return false;
}
if (!idlStructNames.contains(csi.baseValueType))
{
if (!handleIdlStruct(ctti, idlStructNames, idlStructs))
return false;
}
}
else
{
const int idx = csi.baseValueType.indexOf(QLatin1String("::"));
if (idx < 0)
{
ERROR_LOG(m_logger) << "idlStruct '" << csi.baseValueType << "' not found in idl-file";
return false;
}
}
}
else
for (const IdlData& idlData : csi.members)
{
const int idx = csi.baseValueType.indexOf(QLatin1String("::"));
if (idx < 0)
{
ERROR_LOG(m_logger) << "idlStruct '" << csi.baseValueType
<< "' not found in idl-file";
return false;
}
QString idlType;
DEBUG_LOG(m_logger) << "member: " << idlData.type << " - " << idlData.name << " "
<< idlData.dataTypeInfo->isStructure() << " " << idlData.dataTypeInfo->isSequence();
if (idlData.dataTypeInfo->isStructure())
idlType = idlData.dataTypeInfo->idlType();
else if (idlData.dataTypeInfo->isSequence())
{
if (idlData.dataTypeInfo->innerDataType()->isStructure())
idlType = idlData.dataTypeInfo->innerDataType()->idlType();
}
if (idlType.isEmpty())
continue;
if (!handleIdlStruct(m_structBuilder->topicTypeInformationByStructType(idlType, false), idlStructNames,
idlStructs))
return false;
}
}
for (const IdlData &idlData : csi.members)
{
QString idlType;
DEBUG_LOG(m_logger) << "member: " << idlData.type << " - " << idlData.name
<< " " << idlData.dataTypeInfo->isStructure()
<< " " << idlData.dataTypeInfo->isSequence();
if (idlData.dataTypeInfo->isStructure())
idlType = idlData.dataTypeInfo->idlType();
else if (idlData.dataTypeInfo->isSequence())
{
if (idlData.dataTypeInfo->innerDataType()->isStructure())
idlType = idlData.dataTypeInfo->innerDataType()->idlType();
}
if (idlType.isEmpty())
continue;
if (!handleIdlStruct(m_structBuilder->topicTypeInformationByStructType(idlType,
false),
idlStructNames,
idlStructs))
return false;
}
DEBUG_LOG(m_logger) << "Current structName: " << csi.name;
idlStructs += new IdlStructWrapper(csi, this);
DEBUG_LOG(m_logger) << "Current structName: " << csi.name;
idlStructs += new IdlStructWrapper(csi, this);
idlStructNames.insert(csi.name);
idlStructNames.insert(csi.name);
return true;
return true;
}
bool CppTopicGeneratorGrantlee::initIdlStructs()
{
const QVector<CompleteTopicTypeInformation> csiData = m_structBuilder->topicTypeInformations();
QSet<QString> idlStructNames;
QVector<IdlStructWrapper *> idlStructs;
idlStructs.reserve(csiData.size());
for (const CompleteTopicTypeInformation &csi : csiData)
{
if (!handleIdlStruct(csi, idlStructNames, idlStructs))
return false;
}
m_ctx->insert(QStringLiteral("idl_structs"), QVariant::fromValue(idlStructs));
const QVector<CompleteTopicTypeInformation> csiData = m_structBuilder->topicTypeInformations();
const QVector<EnumInformation> enumerations = m_structBuilder->enumInformations();
QVector<IdlEnumWrapper *> idlEnumerations;
idlEnumerations.reserve(enumerations.size());
for (const EnumInformation &ei : enumerations)
idlEnumerations += new IdlEnumWrapper(ei, this);
m_ctx->insert(QStringLiteral("idl_enums"), QVariant::fromValue(idlEnumerations));
QSet<QString> idlStructNames;
QVector<IdlStructWrapper*> idlStructs;
idlStructs.reserve(csiData.size());
for (const CompleteTopicTypeInformation& csi : csiData)
{
if (!handleIdlStruct(csi, idlStructNames, idlStructs))
return false;
}
exportUsedServices(m_reader);
return true;
m_ctx->insert(QStringLiteral("idl_structs"), QVariant::fromValue(idlStructs));
const QVector<EnumInformation> enumerations = m_structBuilder->enumInformations();
QVector<IdlEnumWrapper*> idlEnumerations;
idlEnumerations.reserve(enumerations.size());
for (const EnumInformation& ei : enumerations)
idlEnumerations += new IdlEnumWrapper(ei, this);
m_ctx->insert(QStringLiteral("idl_enums"), QVariant::fromValue(idlEnumerations));
exportUsedServices(m_reader);
return true;
}
CompleteTopicTypeInformation CppTopicGeneratorGrantlee::topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation &tti) const
CompleteTopicTypeInformation
CppTopicGeneratorGrantlee::topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation& tti) const
{
if (tti.baseValueType.isEmpty())
return CompleteTopicTypeInformation();
QString baseValueType = tti.baseValueType;
if (tti.name.contains(QLatin1String("::")) &&
!tti.baseValueType.contains(QLatin1String("::")))
{
const QStringList sl = tti.name.split(QStringLiteral("::"));
baseValueType = sl.at(0) + QLatin1String("::") + tti.baseValueType;
}
DEBUG_LOG(m_logger) << "topicTypeInformationByStructName(" << baseValueType << ")";
return m_structBuilder->topicTypeInformationByStructType(baseValueType);
if (tti.baseValueType.isEmpty())
return CompleteTopicTypeInformation();
QString baseValueType = tti.baseValueType;
if (tti.name.contains(QLatin1String("::")) && !tti.baseValueType.contains(QLatin1String("::")))
{
const QStringList sl = tti.name.split(QStringLiteral("::"));
baseValueType = sl.at(0) + QLatin1String("::") + tti.baseValueType;
}
DEBUG_LOG(m_logger) << "topicTypeInformationByStructName(" << baseValueType << ")";
return m_structBuilder->topicTypeInformationByStructType(baseValueType);
}
+26 -32
View File
@@ -1,47 +1,41 @@
#pragma once
#include <QObject>
#include "GeneratorGrantleeBase.h"
#include "StructBuilder.h"
#include "GrantleeWrappers.h"
#include "StructBuilder.h"
#include <QObject>
namespace CodeGen
{
class CppTopicGeneratorGrantlee final : public GeneratorGrantleeBase
{
Q_OBJECT
public:
explicit CppTopicGeneratorGrantlee();
Q_OBJECT
public:
explicit CppTopicGeneratorGrantlee();
bool init(const XmlReader *reader, StructBuilder *structBuilder) override;
bool init(const XmlReader* reader, StructBuilder* structBuilder) override;
private:
bool initDataTopics();
bool getSpecialColumns(const CompleteTopicTypeInformation &tti,
QVector<IdlData> &keyColumns,
QVector<IdlData> &trColumns) const;
bool initFunctionTopics();
bool handleStruct(const FunctionTopic &ft,
FunctionTopicsWrapper *functionTopicsWrapper);
bool addRequesterRequestParams(const QString &request_name,
const CompleteTopicTypeInformation &request,
FunctionTopicWrapper *ftw);
bool addRequesterReplyParams(const QString &request_name,
const CompleteTopicTypeInformation &reply,
FunctionTopicWrapper *ftw);
bool handleIdlStruct(const CompleteTopicTypeInformation &csi,
QSet<QString> &idlStructNames,
QVector<IdlStructWrapper *> &idlStructs);
bool initIdlStructs();
CompleteTopicTypeInformation topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation &tti) const;
private:
bool initDataTopics();
bool getSpecialColumns(const CompleteTopicTypeInformation& tti, QVector<IdlData>& keyColumns,
QVector<IdlData>& trColumns) const;
const XmlReader *m_reader = nullptr;
bool initFunctionTopics();
bool handleStruct(const FunctionTopic& ft, FunctionTopicsWrapper* functionTopicsWrapper);
bool addRequesterRequestParams(const QString& request_name, const CompleteTopicTypeInformation& request,
FunctionTopicWrapper* ftw);
bool addRequesterReplyParams(const QString& request_name, const CompleteTopicTypeInformation& reply,
FunctionTopicWrapper* ftw);
bool handleIdlStruct(const CompleteTopicTypeInformation& csi, QSet<QString>& idlStructNames,
QVector<IdlStructWrapper*>& idlStructs);
bool initIdlStructs();
CompleteTopicTypeInformation topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation& tti) const;
const XmlReader* m_reader = nullptr;
};
}
} // namespace CodeGen
+35 -38
View File
@@ -1,57 +1,54 @@
#include "DaoGeneratorGrantlee.h"
#include "StructBuilder.h"
#include <NGLLogger/INGLLogger.h>
#include <grantlee/context.h>
using namespace CodeGen;
DaoGeneratorGrantlee::DaoGeneratorGrantlee()
: GeneratorGrantleeBase("CodeGen.DaoGeneratorGrantlee")
{}
DaoGeneratorGrantlee::DaoGeneratorGrantlee() : GeneratorGrantleeBase("CodeGen.DaoGeneratorGrantlee") {}
bool DaoGeneratorGrantlee::init(const XmlReader *reader,
StructBuilder *structBuilder)
bool DaoGeneratorGrantlee::init(const XmlReader* reader, StructBuilder* structBuilder)
{
if (!GeneratorGrantleeBase::initInternal(reader, structBuilder))
return false;
if (!GeneratorGrantleeBase::initInternal(reader, structBuilder))
return false;
if (reader->isServiceExerciseIndependent())
m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1"));
if (reader->isServiceExerciseIndependent())
m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1"));
bool bHasDbNotifications = false;
QVector<DbStructWrapper *> vlServiceStructs;
QVector<DbStructWrapper *> vlStaticDataStructs;
const QVector<CompleteStructInformation> csiData = structBuilder->structInformations();
vlServiceStructs.reserve(csiData.size());
vlStaticDataStructs.reserve(csiData.size());
for (const CompleteStructInformation &csi : csiData)
{
DbStructWrapper *dbStructWrapper(new DbStructWrapper(csi, this));
bool bHasDbNotifications = false;
QVector<DbStructWrapper*> vlServiceStructs;
QVector<DbStructWrapper*> vlStaticDataStructs;
const QVector<CompleteStructInformation> csiData = structBuilder->structInformations();
vlServiceStructs.reserve(csiData.size());
vlStaticDataStructs.reserve(csiData.size());
for (const CompleteStructInformation& csi : csiData)
{
DbStructWrapper* dbStructWrapper(new DbStructWrapper(csi, this));
if (csi.hasStaticContent)
vlStaticDataStructs += dbStructWrapper;
else
vlServiceStructs += dbStructWrapper;
if (!csi.dbNotifications.isEmpty())
bHasDbNotifications = true;
}
if (csi.hasStaticContent)
vlStaticDataStructs += dbStructWrapper;
else
vlServiceStructs += dbStructWrapper;
if (!csi.dbNotifications.isEmpty())
bHasDbNotifications = true;
}
if (structBuilder->needPoint3d())
m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1"));
if (structBuilder->needPgArrayInclude())
m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1"));
m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs));
m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs));
if (bHasDbNotifications)
m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1"));
if (structBuilder->needPoint3d())
m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1"));
if (structBuilder->needPgArrayInclude())
m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1"));
m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs));
m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs));
if (bHasDbNotifications)
m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1"));
m_ctx->insert(QStringLiteral("library_target"), QStringLiteral("COMMON"));
m_ctx->insert(QStringLiteral("library_target"), QStringLiteral("COMMON"));
exportUsedServices(reader);
exportUsedServices(reader);
return true;
return true;
}
+8 -9
View File
@@ -1,11 +1,11 @@
#pragma once
#include <QObject>
#include "GeneratorGrantleeBase.h"
#include "StructBuilder.h"
#include "GrantleeWrappers.h"
#include "StructBuilder.h"
#include <QObject>
namespace CodeGen
{
@@ -13,13 +13,12 @@ struct CompleteStructInformation;
class StructBuilder;
class XmlReader;
class DaoGeneratorGrantlee final : public GeneratorGrantleeBase
{
Q_OBJECT
public:
explicit DaoGeneratorGrantlee();
Q_OBJECT
public:
explicit DaoGeneratorGrantlee();
bool init(const XmlReader *reader, StructBuilder *structBuilder) override;
bool init(const XmlReader* reader, StructBuilder* structBuilder) override;
};
}
} // namespace CodeGen
+47 -47
View File
@@ -1,59 +1,59 @@
#include "DatabaseGeneratorGrantlee.h"
#include "StructBuilder.h"
#include <NGLLogger/INGLLogger.h>
#include <grantlee/context.h>
using namespace CodeGen;
DatabaseGeneratorGrantlee::DatabaseGeneratorGrantlee(bool targetIsServer)
: GeneratorGrantleeBase("CodeGen.CppStructGeneratorGrantlee")
, m_targetIsServer(targetIsServer)
{}
bool DatabaseGeneratorGrantlee::init(const XmlReader *reader,
StructBuilder *structBuilder)
: GeneratorGrantleeBase("CodeGen.CppStructGeneratorGrantlee"), m_targetIsServer(targetIsServer)
{
if (!GeneratorGrantleeBase::initInternal(reader, structBuilder))
return false;
if (reader->isServiceExerciseIndependent())
m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1"));
bool bHasDbNotifications = false;
QVector<DbStructWrapper *> vlServiceStructs;
QVector<DbStructWrapper *> vlStaticDataStructs;
const QVector<CompleteStructInformation> csiData = structBuilder->structInformations();
vlServiceStructs.reserve(csiData.size());
vlStaticDataStructs.reserve(csiData.size());
for (const CompleteStructInformation &csi : csiData)
{
DbStructWrapper *dbStructWrapper(new DbStructWrapper(csi, this));
if (csi.hasStaticContent)
vlStaticDataStructs += dbStructWrapper;
else
vlServiceStructs += dbStructWrapper;
if (!csi.dbNotifications.isEmpty())
bHasDbNotifications = true;
}
addCustomFunctions(reader->getCustomFunctions());
if (structBuilder->needPoint3d())
m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1"));
if (structBuilder->needPgArrayInclude())
m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1"));
m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs));
m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs));
if (bHasDbNotifications)
m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1"));
m_ctx->insert(QStringLiteral("library_target"), m_targetIsServer ? QStringLiteral("SERVER") : QStringLiteral("COMMON"));
exportUsedServices(reader);
return true;
}
bool DatabaseGeneratorGrantlee::init(const XmlReader* reader, StructBuilder* structBuilder)
{
if (!GeneratorGrantleeBase::initInternal(reader, structBuilder))
return false;
if (reader->isServiceExerciseIndependent())
m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1"));
bool bHasDbNotifications = false;
QVector<DbStructWrapper*> vlServiceStructs;
QVector<DbStructWrapper*> vlStaticDataStructs;
const QVector<CompleteStructInformation> csiData = structBuilder->structInformations();
vlServiceStructs.reserve(csiData.size());
vlStaticDataStructs.reserve(csiData.size());
for (const CompleteStructInformation& csi : csiData)
{
DbStructWrapper* dbStructWrapper(new DbStructWrapper(csi, this));
if (csi.hasStaticContent)
vlStaticDataStructs += dbStructWrapper;
else
vlServiceStructs += dbStructWrapper;
if (!csi.dbNotifications.isEmpty())
bHasDbNotifications = true;
}
addCustomFunctions(reader->getCustomFunctions());
if (structBuilder->needPoint3d())
m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1"));
if (structBuilder->needPgArrayInclude())
m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1"));
m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs));
m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs));
if (bHasDbNotifications)
m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1"));
m_ctx->insert(QStringLiteral("library_target"),
m_targetIsServer ? QStringLiteral("SERVER") : QStringLiteral("COMMON"));
exportUsedServices(reader);
return true;
}
+11 -11
View File
@@ -1,11 +1,11 @@
#pragma once
#include <QObject>
#include "GeneratorGrantleeBase.h"
#include "StructBuilder.h"
#include "GrantleeWrappers.h"
#include "StructBuilder.h"
#include <QObject>
namespace CodeGen
{
@@ -13,15 +13,15 @@ struct CompleteStructInformation;
class StructBuilder;
class XmlReader;
class DatabaseGeneratorGrantlee final : public GeneratorGrantleeBase
{
Q_OBJECT
public:
explicit DatabaseGeneratorGrantlee(bool targetIsServer);
Q_OBJECT
public:
explicit DatabaseGeneratorGrantlee(bool targetIsServer);
bool init(const XmlReader *reader, StructBuilder *structBuilder) override;
private:
bool m_targetIsServer;
bool init(const XmlReader* reader, StructBuilder* structBuilder) override;
private:
bool m_targetIsServer;
};
}
} // namespace CodeGen
+147 -149
View File
@@ -1,9 +1,10 @@
#include "GeneratorGrantleeBase.h"
#include "XmlReader.h"
#include "GrantleeWrappers.h"
#include "XmlReader.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QFile>
#include <QRegularExpression>
@@ -11,190 +12,187 @@
#include <grantlee/engine.h>
using namespace CodeGen;
GeneratorGrantleeBase::GeneratorGrantleeBase(const char *loggerName) : m_engine(new Grantlee::Engine)
, m_ctx(new Grantlee::Context)
, m_structBuilder(nullptr)
.getNGLLogger(loggerName)),
m_logger(NGL::NGLLoggerBootstrap::getLogger()) {
m_logger(NGL::NGLLoggerBootstrap::getLogger())
{
}
GeneratorGrantleeBase::~GeneratorGrantleeBase()
{
delete m_engine;
delete m_ctx;
delete m_engine;
delete m_ctx;
}
bool GeneratorGrantleeBase::initInternal(const XmlReader *reader, StructBuilder *structBuilder)
bool GeneratorGrantleeBase::initInternal(const XmlReader* reader, StructBuilder* structBuilder)
{
m_structBuilder = structBuilder;
m_structBuilder = structBuilder;
if (reader)
{
m_ctx->insert(QStringLiteral("namespace"), reader->getServiceNamespace());
m_ctx->insert(QStringLiteral("namespace_abbr"), reader->getServiceAbbr().toLower());
m_ctx->insert(QStringLiteral("namespace_abbr_upper"), reader->getServiceAbbr().toUpper());
if (reader->getServiceNamespace() == QLatin1String("Core"))
m_ctx->insert(QStringLiteral("include_prefix"), QStringLiteral("DDS/%1").arg(reader->getServiceNamespace()));
else
m_ctx->insert(QStringLiteral("include_prefix"), reader->getServiceNamespace());
m_ctx->insert(QStringLiteral("custom_record_replay"), reader->hasCustomRecordReplayPlugin());
}
return true;
if (reader)
{
m_ctx->insert(QStringLiteral("namespace"), reader->getServiceNamespace());
m_ctx->insert(QStringLiteral("namespace_abbr"), reader->getServiceAbbr().toLower());
m_ctx->insert(QStringLiteral("namespace_abbr_upper"), reader->getServiceAbbr().toUpper());
if (reader->getServiceNamespace() == QLatin1String("Core"))
m_ctx->insert(QStringLiteral("include_prefix"),
QStringLiteral("DDS/%1").arg(reader->getServiceNamespace()));
else
m_ctx->insert(QStringLiteral("include_prefix"), reader->getServiceNamespace());
m_ctx->insert(QStringLiteral("custom_record_replay"), reader->hasCustomRecordReplayPlugin());
}
return true;
}
bool GeneratorGrantleeBase::setTemplate(const QString &templateName, const QString &tmpl)
bool GeneratorGrantleeBase::setTemplate(const QString& templateName, const QString& tmpl)
{
m_template = m_engine->newTemplate(tmpl, QStringLiteral("myTemplate"));
if (m_template->error())
{
WARNING_LOG(m_logger) << "Error parsing template '" << templateName
<< "': " << m_template->errorString();
return false;
}
return true;
m_template = m_engine->newTemplate(tmpl, QStringLiteral("myTemplate"));
if (m_template->error())
{
WARNING_LOG(m_logger) << "Error parsing template '" << templateName << "': " << m_template->errorString();
return false;
}
return true;
}
QString GeneratorGrantleeBase::render() const
{
QString out = m_template->render(m_ctx);
const QRegularExpression rx(QLatin1String(";\\n([ ]+\\n)*"));
out = out.replace(rx, QStringLiteral(";\n"));
return out;
QString out = m_template->render(m_ctx);
const QRegularExpression rx(QLatin1String(";\\n([ ]+\\n)*"));
out = out.replace(rx, QStringLiteral(";\n"));
return out;
}
QString GeneratorGrantleeBase::errorString() const
{
return m_template->errorString();
return m_template->errorString();
}
bool GeneratorGrantleeBase::generateData(const QString &templateName,
const QString &outDirectory)
bool GeneratorGrantleeBase::generateData(const QString& templateName, const QString& outDirectory)
{
QString content;
if (!readFile(templateName, content))
return false;
if (!setTemplate(templateName, content))
return false;
QString content;
if (!readFile(templateName, content))
return false;
if (!setTemplate(templateName, content))
return false;
content = render();
content = render();
QString outFilename;
if (!getFilenameFromData(content, outFilename))
return false;
QString outFilename;
if (!getFilenameFromData(content, outFilename))
return false;
QFile f(outDirectory + QLatin1Char('/') + outFilename);
if (!f.open(QIODevice::WriteOnly))
{
ERROR_LOG(m_logger) << "Error opening file '" << f.fileName() << "' for writing: "
<< f.errorString() << "(" << f.error() << ")";
return false;
}
const QByteArray outData = content.toUtf8();
f.write(outData);
f.close();
DEBUG_LOG(m_logger) << "Written data to " << f.fileName();
return true;
}
bool GeneratorGrantleeBase::readFile(const QString &filename, QString &data) const
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly))
{
ERROR_LOG(m_logger) << "Error opening file " << filename
<< " - error: " << f.errorString();
return false;
}
data = QString::fromUtf8(f.readAll());
f.close();
return true;
}
bool GeneratorGrantleeBase::getFilenameFromData(const QString &dataToParse, QString &filename) const
{
const QString filenameMarker(QStringLiteral("// filename:"));
int idx = dataToParse.indexOf(filenameMarker);
if (idx < 0)
{
ERROR_LOG(m_logger) << "Could not find marker '" << filenameMarker
<< "' in data!";
return false;
}
idx += filenameMarker.length() + 1;
int endIdx = dataToParse.indexOf(QLatin1Char('\n'), idx);
if (endIdx < 0)
{
ERROR_LOG(m_logger) << "Could not find end marker '\\n' in data!";
return false;
}
filename = dataToParse.mid(idx, endIdx - idx).trimmed();
return true;
}
void GeneratorGrantleeBase::addCustomFunctions(const QVector<CustomServiceFunctionInformation> &customFunctions)
{
QVariantList vlCustomDbFunctions;
QVariantList vlCustomDtcFunctions;
vlCustomDbFunctions.reserve(customFunctions.size());
vlCustomDtcFunctions.reserve(customFunctions.size());
for (const CustomServiceFunctionInformation &csfi : customFunctions)
{
const QString signature(csfi.returnValue + QLatin1Char(' ') +
csfi.methodName + QLatin1Char('(') + csfi.signature + QLatin1Char(')') +
(csfi.isConst ? QStringLiteral(" const") : QString()));
CustomFunctionWrapper *customFunctionWrapper(new CustomFunctionWrapper(signature, this));
switch (csfi.type)
QFile f(outDirectory + QLatin1Char('/') + outFilename);
if (!f.open(QIODevice::WriteOnly))
{
case CustomServiceFunctionInformation::Type::Db:
vlCustomDbFunctions += QVariant::fromValue(customFunctionWrapper);
break;
case CustomServiceFunctionInformation::Type::Dtc:
vlCustomDtcFunctions += QVariant::fromValue(customFunctionWrapper);
break;
case CustomServiceFunctionInformation::Type::DbNotify:
WARNING_LOG(m_logger) << "Internal error - Trying to handle DbNotify in addCustomFunctions(): "
<< csfi.methodName;
delete customFunctionWrapper;
break;
ERROR_LOG(m_logger) << "Error opening file '" << f.fileName() << "' for writing: " << f.errorString() << "("
<< f.error() << ")";
return false;
}
DEBUG_LOG(m_logger) << "Added custom db function " << csfi.methodName;
}
m_ctx->insert(QStringLiteral("custom_dtc_procs"), vlCustomDtcFunctions);
m_ctx->insert(QStringLiteral("custom_db_procs"), vlCustomDbFunctions);
const QByteArray outData = content.toUtf8();
f.write(outData);
f.close();
DEBUG_LOG(m_logger) << "Written data to " << f.fileName();
return true;
}
void GeneratorGrantleeBase::exportUsedServices(const XmlReader *reader)
bool GeneratorGrantleeBase::readFile(const QString& filename, QString& data) const
{
IdlServicesWrapper *idlServicesWrapper(new IdlServicesWrapper(QString(), this));
const QMap<QString, bool> usedServices = reader->usedServices();
for (auto it = usedServices.begin(); it != usedServices.end(); ++it)
{
if (!it.value())
continue;
const QString &svc = it.key();
const QString fullPath = reader->idlFileForService(svc);
const int idx = fullPath.lastIndexOf(QLatin1Char('.'));
QFile f(filename);
if (!f.open(QIODevice::ReadOnly))
{
ERROR_LOG(m_logger) << "Error opening file " << filename << " - error: " << f.errorString();
return false;
}
data = QString::fromUtf8(f.readAll());
f.close();
return true;
}
bool GeneratorGrantleeBase::getFilenameFromData(const QString& dataToParse, QString& filename) const
{
const QString filenameMarker(QStringLiteral("// filename:"));
int idx = dataToParse.indexOf(filenameMarker);
if (idx < 0)
{
ERROR_LOG(m_logger) << "Could not parse file path: " << fullPath;
continue;
ERROR_LOG(m_logger) << "Could not find marker '" << filenameMarker << "' in data!";
return false;
}
const QString idlFile = fullPath.left(idx);
if (idlFile.isEmpty())
idx += filenameMarker.length() + 1;
int endIdx = dataToParse.indexOf(QLatin1Char('\n'), idx);
if (endIdx < 0)
{
WARNING_LOG(m_logger) << "Could not find idl file for service " << svc;
continue;
ERROR_LOG(m_logger) << "Could not find end marker '\\n' in data!";
return false;
}
idlServicesWrapper->addService(svc, idlFile);
DEBUG_LOG(m_logger) << "Added service " << svc;
}
m_ctx->insert(QStringLiteral("ext_services"), idlServicesWrapper);
filename = dataToParse.mid(idx, endIdx - idx).trimmed();
return true;
}
void GeneratorGrantleeBase::addCustomFunctions(const QVector<CustomServiceFunctionInformation>& customFunctions)
{
QVariantList vlCustomDbFunctions;
QVariantList vlCustomDtcFunctions;
vlCustomDbFunctions.reserve(customFunctions.size());
vlCustomDtcFunctions.reserve(customFunctions.size());
for (const CustomServiceFunctionInformation& csfi : customFunctions)
{
const QString signature(csfi.returnValue + QLatin1Char(' ') + csfi.methodName + QLatin1Char('(') +
csfi.signature + QLatin1Char(')') +
(csfi.isConst ? QStringLiteral(" const") : QString()));
CustomFunctionWrapper* customFunctionWrapper(new CustomFunctionWrapper(signature, this));
switch (csfi.type)
{
case CustomServiceFunctionInformation::Type::Db:
vlCustomDbFunctions += QVariant::fromValue(customFunctionWrapper);
break;
case CustomServiceFunctionInformation::Type::Dtc:
vlCustomDtcFunctions += QVariant::fromValue(customFunctionWrapper);
break;
case CustomServiceFunctionInformation::Type::DbNotify:
WARNING_LOG(m_logger) << "Internal error - Trying to handle DbNotify in addCustomFunctions(): "
<< csfi.methodName;
delete customFunctionWrapper;
break;
}
DEBUG_LOG(m_logger) << "Added custom db function " << csfi.methodName;
}
m_ctx->insert(QStringLiteral("custom_dtc_procs"), vlCustomDtcFunctions);
m_ctx->insert(QStringLiteral("custom_db_procs"), vlCustomDbFunctions);
}
void GeneratorGrantleeBase::exportUsedServices(const XmlReader* reader)
{
IdlServicesWrapper* idlServicesWrapper(new IdlServicesWrapper(QString(), this));
const QMap<QString, bool> usedServices = reader->usedServices();
for (auto it = usedServices.begin(); it != usedServices.end(); ++it)
{
if (!it.value())
continue;
const QString& svc = it.key();
const QString fullPath = reader->idlFileForService(svc);
const int idx = fullPath.lastIndexOf(QLatin1Char('.'));
if (idx < 0)
{
ERROR_LOG(m_logger) << "Could not parse file path: " << fullPath;
continue;
}
const QString idlFile = fullPath.left(idx);
if (idlFile.isEmpty())
{
WARNING_LOG(m_logger) << "Could not find idl file for service " << svc;
continue;
}
idlServicesWrapper->addService(svc, idlFile);
DEBUG_LOG(m_logger) << "Added service " << svc;
}
m_ctx->insert(QStringLiteral("ext_services"), idlServicesWrapper);
}
+27 -25
View File
@@ -3,6 +3,7 @@
#pragma once
#include "XmlReader.h"
#include <QObject>
#include <QSharedPointer>
@@ -17,37 +18,38 @@ class Context;
class Engine;
class TemplateImpl;
using Template = QSharedPointer<TemplateImpl>;
}
} // namespace Grantlee
namespace CodeGen
{
class StructBuilder;
class GeneratorGrantleeBase : public QObject
{
Q_OBJECT
public:
virtual ~GeneratorGrantleeBase();
virtual bool init(const XmlReader *reader, StructBuilder *structBuilder) = 0;
bool setTemplate(const QString &templateName, const QString &tmpl);
QString render() const;
QString errorString() const;
bool generateData(const QString &templateName,
const QString &outDirectory);
Q_OBJECT
public:
virtual ~GeneratorGrantleeBase();
virtual bool init(const XmlReader* reader, StructBuilder* structBuilder) = 0;
bool setTemplate(const QString& templateName, const QString& tmpl);
QString render() const;
QString errorString() const;
bool generateData(const QString& templateName, const QString& outDirectory);
protected:
NGL::INGLLogger &m_logger;
explicit GeneratorGrantleeBase(const char *loggerName);
protected:
NGL::INGLLogger& m_logger;
explicit GeneratorGrantleeBase(const char* loggerName);
bool initInternal(const XmlReader *reader, StructBuilder *structBuilder);
bool readFile(const QString &filename, QString &data) const;
bool getFilenameFromData(const QString &dataToParse, QString &filename) const;
void addCustomFunctions(const QVector<CustomServiceFunctionInformation> &customFunctions);
void exportUsedServices(const XmlReader *reader);
protected:
NGL::INGLLogger &m_logger;
Grantlee::Engine *m_engine;
Grantlee::Context *m_ctx;
Grantlee::Template m_template;
StructBuilder *m_structBuilder;
bool initInternal(const XmlReader* reader, StructBuilder* structBuilder);
bool readFile(const QString& filename, QString& data) const;
bool getFilenameFromData(const QString& dataToParse, QString& filename) const;
void addCustomFunctions(const QVector<CustomServiceFunctionInformation>& customFunctions);
void exportUsedServices(const XmlReader* reader);
protected:
NGL::INGLLogger& m_logger;
Grantlee::Engine* m_engine;
Grantlee::Context* m_ctx;
Grantlee::Template m_template;
StructBuilder* m_structBuilder;
};
}
} // namespace CodeGen
+133 -180
View File
@@ -1,7 +1,7 @@
#include "GrantleeWrappers.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <utility>
@@ -10,241 +10,194 @@ using namespace CodeGen;
#ifdef RTI_HEADER_AVAILABLE
QString IdlStructWrapper::extensibility2String(dds::core::xtypes::ExtensibilityKind extensiblity)
{
switch (extensiblity.underlying())
{
case dds::core::xtypes::ExtensibilityKind_def::FINAL:
return QStringLiteral("FINAL_EXTENSIBILITY");
case dds::core::xtypes::ExtensibilityKind_def::MUTABLE:
return QStringLiteral("MUTABLE_EXTENSIBILITY");
case dds::core::xtypes::ExtensibilityKind_def::EXTENSIBLE:
return QStringLiteral("EXTENSIBLE_EXTENSIBILITY");
}
Q_ASSERT_X(false, "IdlStructWrapper::extensibility2String", "Unknown extensiblity kind");
return QString();
switch (extensiblity.underlying())
{
case dds::core::xtypes::ExtensibilityKind_def::FINAL:
return QStringLiteral("FINAL_EXTENSIBILITY");
case dds::core::xtypes::ExtensibilityKind_def::MUTABLE:
return QStringLiteral("MUTABLE_EXTENSIBILITY");
case dds::core::xtypes::ExtensibilityKind_def::EXTENSIBLE:
return QStringLiteral("EXTENSIBLE_EXTENSIBILITY");
}
Q_ASSERT_X(false, "IdlStructWrapper::extensibility2String", "Unknown extensiblity kind");
return QString();
}
#else
QString IdlStructWrapper::extensibility2String(int /*extensiblity*/)
{
// RTI not available - return placeholder
return QStringLiteral("EXTENSIBLE_EXTENSIBILITY");
// RTI not available - return placeholder
return QStringLiteral("EXTENSIBLE_EXTENSIBILITY");
}
#endif
QString DataTopicWrapper::typeFq() const
{
const QString &t = type();
const QString &s = serviceName();
if (s.isEmpty())
return t;
if (t.startsWith(s))
return t;
return s + QStringLiteral("::") + t;
const QString& t = type();
const QString& s = serviceName();
if (s.isEmpty())
return t;
if (t.startsWith(s))
return t;
return s + QStringLiteral("::") + t;
}
QString MemberInformationWrapper::ddsToQVariant() const
{
return QStringLiteral("toQVariant(data.") + cppMemberName() + QStringLiteral("())");
return QStringLiteral("toQVariant(data.") + cppMemberName() + QStringLiteral("())");
}
QString MemberInformationWrapper::qVariantToDds() const
{
const QString ddsType = isOptional() ?
(QStringLiteral("dds::core::optional<") + cppDdsType() + QLatin1Char('>')) :
(cppDdsType());
const QString ddsType =
isOptional() ? (QStringLiteral("dds::core::optional<") + cppDdsType() + QLatin1Char('>')) : (cppDdsType());
return QStringLiteral("data.") + cppMemberName() +
QStringLiteral("() = fromQVariant<") + ddsType + QStringLiteral(">(q.value(i++))");
return QStringLiteral("data.") + cppMemberName() + QStringLiteral("() = fromQVariant<") + ddsType +
QStringLiteral(">(q.value(i++))");
}
QString MemberInformationWrapper::ddsToJsonElement() const
{
if (cppMemberName().isEmpty())
return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;");
const QString memberAccess = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()");
if (!isOptional())
return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + cppToJsonPre() +
QStringLiteral("element.") + memberAccess + cppToJsonPost();
if (cppMemberName().isEmpty())
return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;");
const QString memberAccess = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()");
if (!isOptional())
return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") +
cppToJsonPre() + QStringLiteral("element.") + memberAccess + cppToJsonPost();
const QString optionalAccess = isCppStruct() ? cppMemberName() + QStringLiteral(".is_set()") : cppMemberName() + QStringLiteral("().is_set()");
const QString getValue = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()");
return QStringLiteral("if (element.") + optionalAccess + QStringLiteral(") ") +
QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") +
cppToJsonPre() + QStringLiteral("element.") + getValue + cppToJsonPost();
const QString optionalAccess =
isCppStruct() ? cppMemberName() + QStringLiteral(".is_set()") : cppMemberName() + QStringLiteral("().is_set()");
const QString getValue = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()");
return QStringLiteral("if (element.") + optionalAccess + QStringLiteral(") ") +
QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + cppToJsonPre() +
QStringLiteral("element.") + getValue + cppToJsonPost();
}
QString MemberInformationWrapper::jsonElementToDds() const
{
if (cppMemberName().isEmpty())
return QStringLiteral("element = ") + cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") +
cppType() + QStringLiteral("\"))") + cppFromJsonPost();
QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() +
QStringLiteral("\"))); "));
if (isOptional())
ret += QStringLiteral("if (!val.isNull()) ");
if (isCppStruct())
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") + cppFromJsonPre2() +
QStringLiteral("val") + cppFromJsonPost();
else
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral("(") + cppFromJsonPre2() +
QStringLiteral("val") + cppFromJsonPost() + QStringLiteral(")");
if (cppMemberName().isEmpty())
return QStringLiteral("element = ") +
cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") + cppType() + QStringLiteral("\"))") + cppFromJsonPost();
QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() + QStringLiteral("\"))); "));
if (isOptional())
ret += QStringLiteral("if (!val.isNull()) ");
if (isCppStruct())
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") +
cppFromJsonPre2() + QStringLiteral("val") + cppFromJsonPost();
else
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral("(") +
cppFromJsonPre2() + QStringLiteral("val") + cppFromJsonPost() + QStringLiteral(")");
return ret;
return ret;
}
QString MemberInformationWrapper::dbToJsonElement() const
{
if (cppMemberName().isEmpty())
return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;");
if (isOptional() || cppType() == QStringLiteral("QDateTime"))
{
QString ret = QStringLiteral("if (") +
((cppType() == QStringLiteral("QDateTime")) ? QString() : QStringLiteral("!")) +
QStringLiteral("element.") + cppMemberName() +
((cppType() == QStringLiteral("QDateTime")) ? QStringLiteral(".isValid()) ")
: QStringLiteral(".isNull()) ")) +
QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ");
if (isOptional())
return ret += cppFromQvPre2() + QStringLiteral("element.") + cppMemberName() + cppFromQvPost();
}
if (cppMemberName().isEmpty())
return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;");
if (isOptional() || cppType() == QStringLiteral("QDateTime"))
{
QString ret = QStringLiteral("if (") + ((cppType() == QStringLiteral("QDateTime")) ? QString() : QStringLiteral("!")) +
QStringLiteral("element.") + cppMemberName() +
((cppType() == QStringLiteral("QDateTime")) ? QStringLiteral(".isValid()) ") : QStringLiteral(".isNull()) ")) +
QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ");
if (isOptional())
return ret += cppFromQvPre2() + QStringLiteral("element.") + cppMemberName() + cppFromQvPost();
}
return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") +
cppToJsonPre() + QStringLiteral("element.") + cppMemberName() + cppToJsonPost();
return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + cppToJsonPre() +
QStringLiteral("element.") + cppMemberName() + cppToJsonPost();
}
QString MemberInformationWrapper::jsonElementToDb() const
{
if (cppMemberName().isEmpty())
return QStringLiteral("element = ") + cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") +
cppType() + QStringLiteral("\"))") + cppFromJsonPost();
QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() +
QStringLiteral("\"))); "));
if (isOptional())
ret += QStringLiteral("if (!val.isUndefined()) ");
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") + cppFromJsonPre2() +
QStringLiteral("val") + cppFromJsonPost();
if (cppMemberName().isEmpty())
return QStringLiteral("element = ") +
cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") + cppType() + QStringLiteral("\"))") + cppFromJsonPost();
QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() + QStringLiteral("\"))); "));
if (isOptional())
ret += QStringLiteral("if (!val.isUndefined()) ");
ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") +
cppFromJsonPre2() + QStringLiteral("val") + cppFromJsonPost();
return ret;
return ret;
}
QVariantList DbStructWrapper::insertStructures()
{
QStringList tableNames;
QMap<QString, QVector<MemberInformationWrapper *>> structures;
QMap<QString, MemberInformationWrapper *> primaryKeys;
QMap<QString, MemberInformationWrapper *> fkComplexTableKeys;
tableNames.reserve(5);
for (const QVariant &v : std::as_const(m_member))
{
MemberInformationWrapper *mi = v.value<MemberInformationWrapper *>();
const QString &tableName = mi->info().db.table;
if (mi->info().db.usedForInsert)
{
auto &tnStructure = structures[tableName];
tnStructure.append(mi);
if (!tableNames.contains(tableName))
tableNames.push_back(tableName);
}
if (mi->info().fk)
fkComplexTableKeys[mi->info().fk->destination.tableName] = mi;
if (mi->info().db.isPrimaryKey)
{
if (!primaryKeys.contains(tableName))
primaryKeys[tableName] = mi;
}
if (mi->info().db.isAssignmentForPrimaryTablePk)
fkComplexTableKeys[mi->info().db.table] = mi;
}
QVariantList vl;
vl.reserve(tableNames.size());
for (int i = 0; i < tableNames.size(); ++i)
{
const QString &tn = tableNames.at(i);
MemberInformationWrapper *serialMember = fkComplexTableKeys.value(tn);
MemberInformationWrapper *baseId = nullptr;
MemberInformationWrapper *primaryKey = primaryKeys.value(tn);
if (i == 0 && tableNames.size() > 1)
baseId = primaryKeys.value(tn);
QStringList tableNames;
QMap<QString, QVector<MemberInformationWrapper*>> structures;
QMap<QString, MemberInformationWrapper*> primaryKeys;
QMap<QString, MemberInformationWrapper*> fkComplexTableKeys;
if (tableNames.size() == 1)
tableNames.reserve(5);
for (const QVariant& v : std::as_const(m_member))
{
baseId = nullptr;
if (!primaryKey)
{
NGL::INGLLogger &logger = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("DbStructWrapper");
WARNING_LOG(logger) << "Table " << tn << " has no primary key!";
}
else
{
if (primaryKey->dbHasSequence())
serialMember = primaryKey;
}
MemberInformationWrapper* mi = v.value<MemberInformationWrapper*>();
const QString& tableName = mi->info().db.table;
if (mi->info().db.usedForInsert)
{
auto& tnStructure = structures[tableName];
tnStructure.append(mi);
if (!tableNames.contains(tableName))
tableNames.push_back(tableName);
}
if (mi->info().fk)
fkComplexTableKeys[mi->info().fk->destination.tableName] = mi;
if (mi->info().db.isPrimaryKey)
{
if (!primaryKeys.contains(tableName))
primaryKeys[tableName] = mi;
}
if (mi->info().db.isAssignmentForPrimaryTablePk)
fkComplexTableKeys[mi->info().db.table] = mi;
}
const QVector<MemberInformationWrapper *> members = structures.value(tn);
TableWrapper *tw = new TableWrapper(tn, members, serialMember, baseId, primaryKey, this);
vl += QVariant::fromValue(tw);
}
QVariantList vl;
vl.reserve(tableNames.size());
for (int i = 0; i < tableNames.size(); ++i)
{
const QString& tn = tableNames.at(i);
MemberInformationWrapper* serialMember = fkComplexTableKeys.value(tn);
MemberInformationWrapper* baseId = nullptr;
MemberInformationWrapper* primaryKey = primaryKeys.value(tn);
if (i == 0 && tableNames.size() > 1)
baseId = primaryKeys.value(tn);
return vl;
if (tableNames.size() == 1)
{
baseId = nullptr;
if (!primaryKey)
{
NGL::INGLLogger& logger = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("DbStructWrapper");
WARNING_LOG(logger) << "Table " << tn << " has no primary key!";
}
else
{
if (primaryKey->dbHasSequence())
serialMember = primaryKey;
}
}
const QVector<MemberInformationWrapper*> members = structures.value(tn);
TableWrapper* tw = new TableWrapper(tn, members, serialMember, baseId, primaryKey, this);
vl += QVariant::fromValue(tw);
}
return vl;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+144 -120
View File
@@ -2,11 +2,12 @@
#pragma once
#include <QStringList>
#include <QSharedPointer>
#include "StructBuilder.h"
#include "codegen_base_export.h"
#include <QSharedPointer>
#include <QStringList>
namespace NGL
{
class INGLLogger;
@@ -23,152 +24,175 @@ class XmlReader;
class CODEGEN_BASE_EXPORT SqlGenerator final
{
public:
struct SqlStatements
{
QStringList dropViews;
QStringList dropTables;
QStringList dropSequences;
QStringList dropConstraints;
QStringList createTables;
QStringList createSequences;
QStringList createPrimaryKeys;
QStringList createForeignKeys;
QStringList createViews;
QStringList createConstraints;
QStringList enumerationValues;
QStringList dbFunctions;
QStringList dbFunctionTrigger;
bool isEmpty() const
public:
struct SqlStatements
{
return dropViews.isEmpty() && dropTables.isEmpty() && dropSequences.isEmpty() && dropConstraints.isEmpty();
QStringList dropViews;
QStringList dropTables;
QStringList dropSequences;
QStringList dropConstraints;
QStringList createTables;
QStringList createSequences;
QStringList createPrimaryKeys;
QStringList createForeignKeys;
QStringList createViews;
QStringList createConstraints;
QStringList enumerationValues;
QStringList dbFunctions;
QStringList dbFunctionTrigger;
bool isEmpty() const
{
return dropViews.isEmpty() && dropTables.isEmpty() && dropSequences.isEmpty() && dropConstraints.isEmpty();
}
};
struct SqlItems
{
QStringList tables;
QStringList sequences;
QStringList primaryKeys;
QStringList foreignKeys;
QStringList constraints;
};
public:
Q_DISABLE_COPY(SqlGenerator)
explicit SqlGenerator(XmlReader* xmlReader, StructBuilder* structBuilder);
explicit SqlGenerator(const QString& xmlFile);
~SqlGenerator();
bool isValid() const
{
return m_isValid;
}
};
struct SqlItems
{
QStringList tables;
QStringList sequences;
QStringList primaryKeys;
QStringList foreignKeys;
QStringList constraints;
};
bool generateData(int exerciseId);
public:
Q_DISABLE_COPY(SqlGenerator)
bool createStatementsForTable(const QString& tableName, const QString& tableNameOut);
explicit SqlGenerator(XmlReader *xmlReader, StructBuilder *structBuilder);
explicit SqlGenerator(const QString &xmlFile);
SqlStatements getStatements(ExerciseDependency ed) const
{
return (ed == ExerciseDependency::Exercise ? m_sqlExercise : m_sqlGlobal);
}
~SqlGenerator();
SqlItems getSqlItems(ExerciseDependency ed) const
{
return (ed == ExerciseDependency::Exercise ? m_sqlItemsExercise : m_sqlItemsGlobal);
}
bool isValid() const { return m_isValid; }
bool generateData(int exerciseId);
QStringList getEnumerationInsertValues(const QString& table, const QString& dbSchema) const;
bool createStatementsForTable(const QString &tableName, const QString &tableNameOut);
QStringList getReferencedServices() const
{
return m_referencedSevices;
}
SqlStatements getStatements(ExerciseDependency ed) const
{
return (ed == ExerciseDependency::Exercise ? m_sqlExercise : m_sqlGlobal);
}
QStringList getDbSettings(const QString& dbSchema) const;
SqlItems getSqlItems(ExerciseDependency ed) const
{
return (ed == ExerciseDependency::Exercise ? m_sqlItemsExercise : m_sqlItemsGlobal);
}
bool writeSql(const QString& filePath, ExerciseDependency ed);
QStringList getEnumerationInsertValues(const QString &table, const QString &dbSchema) const;
QStringList getReferencedServices() const
{
return m_referencedSevices;
}
bool writeSqlToFile(const QString& dbSchema, const QString& sqlFile, ExerciseDependency ed) const;
QStringList getDbSettings(const QString &dbSchema) const;
QString getServiceAbbr() const
{
return m_xmlReader->getServiceAbbr();
}
bool writeSql(const QString &filePath, ExerciseDependency ed);
bool isServiceExerciseIndependent() const
{
return m_xmlReader->isServiceExerciseIndependent();
}
bool writeSqlToFile(const QString &dbSchema, const QString &sqlFile, ExerciseDependency ed) const;
bool isServiceGlobal() const
{
return (m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::Global ||
m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::GlobalAndExercise);
}
QString getServiceAbbr() const { return m_xmlReader->getServiceAbbr(); }
bool isServiceExerciseIndependent() const { return m_xmlReader->isServiceExerciseIndependent(); }
bool isServiceGlobal() const { return (m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::Global || m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::GlobalAndExercise); }
CodeGen::ExerciseDependency getExerciseDependency() const { return m_xmlReader->defaultExerciseDependency();}
QStringList getGroupNames() const { return m_xmlReader->getGroupNames(); }
CodeGen::ExerciseDependency getExerciseDependency() const
{
return m_xmlReader->defaultExerciseDependency();
}
QStringList getAllSqlStmts(const QString &dbSchema, ExerciseDependency ed) const;
QStringList getGroupNames() const
{
return m_xmlReader->getGroupNames();
}
QStringList getAllSqlStmts(const QString& dbSchema, ExerciseDependency ed) const;
protected:
protected:
NGL::INGLLogger& m_logger;
NGL::INGLLogger &m_logger;
private:
bool handleTables();
bool handleViews();
bool handleTable(const CompleteTableInformation &cti);
bool handleView(const ViewInformation &vi);
QString getTableColumnCreateStatements(const QString &tableName,
const QVector<MemberInformation> &columns,
QStringList *tableComments, ExerciseDependency ed);
QString generateSequence(const QString &tableName, const FullQualifiedColumnInformation &ci, ExerciseDependency ed);
void generatePrimaryKey(const QString &tableName, const FullQualifiedColumnInformation &ci, ExerciseDependency ed);
void generateForeignKeys(const QVector<QSharedPointer<ForeignKeyInformation> > &foreignKeys, ExerciseDependency ed);
void generateForeignKey(const QSharedPointer<ForeignKeyInformation> &foreignKey, ExerciseDependency ed);
void generateConstraints(const QString &tableName, const QVector<ConstraintInformation> &constraints, ExerciseDependency ed);
void generateConstraint(const QString &tableName, const ConstraintInformation &constraint, ExerciseDependency ed);
bool handleEnumerations();
bool handleEnumeration(const EnumInformation &ei);
QStringList handleEnumeration(const EnumInformation &ei, const QString &dbSchema) const;
bool generateDbNotifications(const QString &tableName, const QVector<DbNotifcationInformation> &notifications, ExerciseDependency ed);
void generateDbNotification(const DbNotifcationInformation &notification, ExerciseDependency ed);
bool generateDbNotificationTrigger(const QString &tableName, const DbNotifcationInformation &notification, ExerciseDependency ed);
QString getNotificationFunctionName(const DbNotifcationInformation &notification) const;
static QString fixupComment(const QString &comment);
private:
bool handleTables();
bool handleViews();
bool handleTable(const CompleteTableInformation& cti);
bool handleView(const ViewInformation& vi);
QString getTableColumnCreateStatements(const QString& tableName, const QVector<MemberInformation>& columns,
QStringList* tableComments, ExerciseDependency ed);
QString generateSequence(const QString& tableName, const FullQualifiedColumnInformation& ci, ExerciseDependency ed);
void generatePrimaryKey(const QString& tableName, const FullQualifiedColumnInformation& ci, ExerciseDependency ed);
void generateForeignKeys(const QVector<QSharedPointer<ForeignKeyInformation>>& foreignKeys, ExerciseDependency ed);
void generateForeignKey(const QSharedPointer<ForeignKeyInformation>& foreignKey, ExerciseDependency ed);
void generateConstraints(const QString& tableName, const QVector<ConstraintInformation>& constraints,
ExerciseDependency ed);
void generateConstraint(const QString& tableName, const ConstraintInformation& constraint, ExerciseDependency ed);
bool handleEnumerations();
bool handleEnumeration(const EnumInformation& ei);
QStringList handleEnumeration(const EnumInformation& ei, const QString& dbSchema) const;
bool generateDbNotifications(const QString& tableName, const QVector<DbNotifcationInformation>& notifications,
ExerciseDependency ed);
void generateDbNotification(const DbNotifcationInformation& notification, ExerciseDependency ed);
bool generateDbNotificationTrigger(const QString& tableName, const DbNotifcationInformation& notification,
ExerciseDependency ed);
QString getNotificationFunctionName(const DbNotifcationInformation& notification) const;
static QString fixupComment(const QString& comment);
private:
XmlReader *m_xmlReader;
StructBuilder *m_structBuilder;
bool m_createdByXmlFile;
private:
XmlReader* m_xmlReader;
StructBuilder* m_structBuilder;
bool m_createdByXmlFile;
void addToDropSequences(const QString &stmt, ExerciseDependency ed);
void addToDropTables(const QString &stmt, ExerciseDependency ed);
void addToDropViews(const QString &stmt, ExerciseDependency ed);
void addToDropConstraints(const QString &stmt, ExerciseDependency ed);
void addToDropSequences(const QString& stmt, ExerciseDependency ed);
void addToDropTables(const QString& stmt, ExerciseDependency ed);
void addToDropViews(const QString& stmt, ExerciseDependency ed);
void addToDropConstraints(const QString& stmt, ExerciseDependency ed);
void addToCreateConstraints(const QString &stmt, ExerciseDependency ed);
void addToCreateFks(const QString &stmt, ExerciseDependency ed);
void addToCreatePks(const QString &stmt, ExerciseDependency ed);
void addToCreateSequences(const QString &stmt, ExerciseDependency ed);
void addToCreateTables(const QString &stmt, ExerciseDependency ed);
void addToCreateTables(const QStringList &stmts, ExerciseDependency ed);
void addToCreateViews(const QString &stmt, ExerciseDependency ed);
void addToCreateConstraints(const QString& stmt, ExerciseDependency ed);
void addToCreateFks(const QString& stmt, ExerciseDependency ed);
void addToCreatePks(const QString& stmt, ExerciseDependency ed);
void addToCreateSequences(const QString& stmt, ExerciseDependency ed);
void addToCreateTables(const QString& stmt, ExerciseDependency ed);
void addToCreateTables(const QStringList& stmts, ExerciseDependency ed);
void addToCreateViews(const QString& stmt, ExerciseDependency ed);
void addToDbFunctions(const QString &stmt, ExerciseDependency ed);
void addToDbFunctionTrigger(const QString &stmt, ExerciseDependency ed);
void addToDbFunctions(const QString& stmt, ExerciseDependency ed);
void addToDbFunctionTrigger(const QString& stmt, ExerciseDependency ed);
void addToConstraints(const QString &name, ExerciseDependency ed);
void addToFks(const QString &name, ExerciseDependency ed);
void addToPks(const QString &name, ExerciseDependency ed);
void addToSequences(const QString &name, ExerciseDependency ed);
void addToTables(const QString &name, ExerciseDependency ed);
void addToConstraints(const QString& name, ExerciseDependency ed);
void addToFks(const QString& name, ExerciseDependency ed);
void addToPks(const QString& name, ExerciseDependency ed);
void addToSequences(const QString& name, ExerciseDependency ed);
void addToTables(const QString& name, ExerciseDependency ed);
bool writeFile(const QString &fn, const QString &content) const;
bool writeFile(const QString& fn, const QString& content) const;
SqlStatements m_sqlGlobal;
SqlStatements m_sqlExercise;
SqlStatements m_sqlGlobal;
SqlStatements m_sqlExercise;
SqlItems m_sqlItemsGlobal;
SqlItems m_sqlItemsExercise;
SqlItems m_sqlItemsGlobal;
SqlItems m_sqlItemsExercise;
QStringList m_referencedSevices;
QStringList m_referencedSevices;
bool m_isValid;
int m_exerciseId;
bool m_isValid;
int m_exerciseId;
};
}
} // namespace CodeGen
File diff suppressed because it is too large. Load diff
+292 -248
View File
@@ -2,10 +2,11 @@
#pragma once
#include <QtCore/QString>
#include "XmlReader.h"
#include "codegen_base_export.h"
#include <QtCore/QString>
namespace NGL
{
class INGLLogger;
@@ -17,325 +18,368 @@ class StructBuilder;
struct EaData
{
QString table;
QString column;
QString type;
QString table;
QString column;
QString type;
QString toString() const
{
return table +
QLatin1Char(';') + column +
QLatin1Char(';') + type;
}
QString toString() const
{
return table + QLatin1Char(';') + column + QLatin1Char(';') + type;
}
};
struct FullQualifiedColumnInformation : public ColumnInformation
{
QString table;
bool usedForInsert = false;
bool usedForView = false;
QString columnNameView;
QString table;
bool usedForInsert = false;
bool usedForView = false;
QString columnNameView;
QString getColumnNameView() const { return columnNameView.isEmpty() ? columnName : columnNameView; }
QString getColumnNameView() const
{
return columnNameView.isEmpty() ? columnName : columnNameView;
}
FullQualifiedColumnInformation() = default;
FullQualifiedColumnInformation(const ColumnInformation &ci, const QString &tableName)
: ColumnInformation(ci)
, table(tableName)
{}
FullQualifiedColumnInformation() = default;
QString toString() const
{
return table +
QLatin1Char(';') + columnName +
QLatin1Char(';') + datatype +
QLatin1Char(';') + (isPrimaryKey ? QLatin1String("true") : QLatin1String("false")) +
QLatin1Char(';') + (isForeignKey ? QLatin1String("true") : QLatin1String("false")) +
QLatin1Char(';') + (usedForInsert ? QLatin1String("true") : QLatin1String("false")) +
QLatin1Char(';') + (usedForView ? QLatin1String("true") : QLatin1String("false"));
}
FullQualifiedColumnInformation(const ColumnInformation& ci, const QString& tableName)
: ColumnInformation(ci), table(tableName)
{
}
QString toString() const
{
return table + QLatin1Char(';') + columnName + QLatin1Char(';') + datatype +
QLatin1Char(';') + (isPrimaryKey ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') +
(isForeignKey ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') +
(usedForInsert ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') +
(usedForView ? QLatin1String("true") : QLatin1String("false"));
}
};
class DataTypeInfo
{
public:
DataTypeInfo(const QString &name, bool isPod)
: m_name(name)
, m_isPod(isPod)
{}
virtual ~DataTypeInfo() = default;
virtual QString name() const { return m_name; }
virtual QString idlType() const = 0;
virtual QString ddsType() const = 0;
virtual QString sqlType() const = 0;
virtual QString cppType() const = 0;
virtual QString cppTypeConstRef() const { return isPod() ? cppType() : QLatin1String("const ") + cppType() + QLatin1String(" &"); }
virtual bool isPod() const { return m_isPod; }
virtual bool isSequence() const { return false; }
virtual bool isStructure() const { return false; }
virtual QVector<QSharedPointer<DataTypeInfo>> member() const { return QVector<QSharedPointer<DataTypeInfo>>(); }
virtual QSharedPointer<DataTypeInfo> innerDataType() const { return QSharedPointer<DataTypeInfo>(); }
public:
DataTypeInfo(const QString& name, bool isPod) : m_name(name), m_isPod(isPod) {}
static QSharedPointer<DataTypeInfo> fromIdlDataType(const QString &name,
const QString &idlType,
StructBuilder *structBuilder,
const QString &svcName = QString());
protected:
const QString m_name;
const bool m_isPod;
virtual ~DataTypeInfo() = default;
virtual QString name() const
{
return m_name;
}
virtual QString idlType() const = 0;
virtual QString ddsType() const = 0;
virtual QString sqlType() const = 0;
virtual QString cppType() const = 0;
virtual QString cppTypeConstRef() const
{
return isPod() ? cppType() : QLatin1String("const ") + cppType() + QLatin1String(" &");
}
virtual bool isPod() const
{
return m_isPod;
}
virtual bool isSequence() const
{
return false;
}
virtual bool isStructure() const
{
return false;
}
virtual QVector<QSharedPointer<DataTypeInfo>> member() const
{
return QVector<QSharedPointer<DataTypeInfo>>();
}
virtual QSharedPointer<DataTypeInfo> innerDataType() const
{
return QSharedPointer<DataTypeInfo>();
}
static QSharedPointer<DataTypeInfo> fromIdlDataType(const QString& name, const QString& idlType,
StructBuilder* structBuilder,
const QString& svcName = QString());
protected:
const QString m_name;
const bool m_isPod;
};
struct IdlData : public IdlColumnInformation
{
QSharedPointer<DataTypeInfo> dataTypeInfo;
QSharedPointer<DataTypeInfo> dataTypeInfo;
IdlData() = default;
explicit IdlData(const IdlColumnInformation &ci)
: IdlColumnInformation(ci)
{}
IdlData() = default;
QString toString() const
{
return name +
QLatin1Char(';') + type +
QLatin1Char(';') + (isKey ? QLatin1String("true") : QLatin1String("false")) +
QLatin1Char(';') + (isOptional ? QLatin1String("true") : QLatin1String("false"));
}
explicit IdlData(const IdlColumnInformation& ci) : IdlColumnInformation(ci) {}
QString toString() const
{
return name + QLatin1Char(';') + type +
QLatin1Char(';') + (isKey ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') +
(isOptional ? QLatin1String("true") : QLatin1String("false"));
}
};
struct CppData
{
QString structName;
QString memberName;
QString defaultValue;
bool usedForCppStruct = false;
bool usedForJson = false;
bool isReadOnly = false;
bool isOptional = false;
QString type;
QString ddsType;
QString toVariantPre;
QString toVariantPost;
QString fromVariantPre1;
QString fromVariantPre2;
QString fromVariantPost;
QString structName;
QString memberName;
QString defaultValue;
bool usedForCppStruct = false;
bool usedForJson = false;
bool isReadOnly = false;
bool isOptional = false;
QString type;
QString ddsType;
QString toVariantPre;
QString toVariantPost;
QString fromVariantPre1;
QString fromVariantPre2;
QString fromVariantPost;
QString toJsonPre;
QString toJsonPost;
QString fromJsonPre2;
QString fromJsonPost;
QString toJsonPre;
QString toJsonPost;
QString fromJsonPre2;
QString fromJsonPost;
QString toString() const
{
return structName +
QLatin1Char(';') + memberName +
QLatin1Char(';') + (usedForCppStruct ? QLatin1String("true") : QLatin1String("false")) +
QLatin1Char(';') + (isReadOnly ? QLatin1String("true") : QLatin1String("false")) +
QLatin1Char(';') + type +
QLatin1Char(';') + toVariantPre +
QLatin1Char(';') + toVariantPost +
QLatin1Char(';') + fromVariantPre1 +
QLatin1Char(';') + fromVariantPre2 +
QLatin1Char(';') + fromVariantPost;
}
QString toString() const
{
return structName + QLatin1Char(';') + memberName + QLatin1Char(';') +
(usedForCppStruct ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') +
(isReadOnly ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') + type +
QLatin1Char(';') + toVariantPre + QLatin1Char(';') + toVariantPost + QLatin1Char(';') + fromVariantPre1 +
QLatin1Char(';') + fromVariantPre2 + QLatin1Char(';') + fromVariantPost;
}
};
struct MemberInformation
{
EaData ea;
FullQualifiedColumnInformation db;
CppData cpp;
bool isDdsKey = false;
QSharedPointer<ForeignKeyInformation> fk;
QSharedPointer<EnumInformation> enumeration;
EaData ea;
FullQualifiedColumnInformation db;
CppData cpp;
bool isDdsKey = false;
QSharedPointer<ForeignKeyInformation> fk;
QSharedPointer<EnumInformation> enumeration;
QString toString() const
{
return ea.toString() + QLatin1Char(';') +
db.toString() + QLatin1Char(';') +
cpp.toString();
}
bool isEmpty() const
{
return ea.column.isEmpty();
}
QString toString() const
{
return ea.toString() + QLatin1Char(';') + db.toString() + QLatin1Char(';') + cpp.toString();
}
bool isEmpty() const
{
return ea.column.isEmpty();
}
};
struct CompleteStructInformation
{
QString structName;
QString viewName;
QSet<QSharedPointer<TableInformation> > tables;
QSharedPointer<TableInformation> primaryTable;
QVector<MemberInformation> member;
QVector<DbNotifcationInformation> dbNotifications;
bool hasStaticContent = false;
QString structName;
QString viewName;
QSet<QSharedPointer<TableInformation>> tables;
QSharedPointer<TableInformation> primaryTable;
QVector<MemberInformation> member;
QVector<DbNotifcationInformation> dbNotifications;
bool hasStaticContent = false;
bool isEmpty() const
{
return primaryTable.isNull();
}
bool isEmpty() const
{
return primaryTable.isNull();
}
};
struct CompleteTopicTypeInformation final : public TopicTypeInformationBase
{
QString serviceName;
QString serviceName;
QVector<IdlData> members;
QVector<IdlData> members;
CompleteTopicTypeInformation() = default;
explicit CompleteTopicTypeInformation(const TopicTypeInformationBase &s)
: TopicTypeInformationBase(s)
{}
CompleteTopicTypeInformation() = default;
bool hasBaseValue() const { return !baseValueType.isEmpty(); }
bool isValid() const { return TopicTypeInformationBase::isValid() && !members.isEmpty(); }
explicit CompleteTopicTypeInformation(const TopicTypeInformationBase& s) : TopicTypeInformationBase(s) {}
bool hasBaseValue() const
{
return !baseValueType.isEmpty();
}
bool isValid() const
{
return TopicTypeInformationBase::isValid() && !members.isEmpty();
}
};
struct CompleteTableInformation : public TableInformation
{
QVector<MemberInformation> columns;
explicit CompleteTableInformation(const TableInformation &o)
: TableInformation(o)
{}
CompleteTableInformation() = default;
bool isEmpty() const { return columns.isEmpty(); }
QVector<MemberInformation> columns;
explicit CompleteTableInformation(const TableInformation& o) : TableInformation(o) {}
CompleteTableInformation() = default;
bool isEmpty() const
{
return columns.isEmpty();
}
};
class CODEGEN_BASE_EXPORT StructBuilder
{
struct ColumnInformationEx : public ColumnInformation
{
QSharedPointer<TableInformation> table;
struct ColumnInformationEx : public ColumnInformation
{
QSharedPointer<TableInformation> table;
ColumnInformationEx() = default;
ColumnInformationEx(const ColumnInformation &o,
const QSharedPointer<TableInformation> &ti)
: ColumnInformation(o)
, table(ti)
{}
};
ColumnInformationEx() = default;
public:
struct ServiceTypeStruct
{
QString service;
QString type;
bool bIsSequence = false;
bool isExternalType() const { return !service.isEmpty(); }
bool isSequence() const { return bIsSequence; }
QString fqType() const { return service + QStringLiteral("::") + type; }
};
ColumnInformationEx(const ColumnInformation& o, const QSharedPointer<TableInformation>& ti)
: ColumnInformation(o), table(ti)
{
}
};
explicit StructBuilder(XmlReader *xmlReader);
~StructBuilder() = default;
public:
struct ServiceTypeStruct
{
QString service;
QString type;
bool bIsSequence = false;
bool buildStructures();
QVector<CompleteStructInformation> structInformations() const
{
return m_structInfos;
}
QVector<CompleteTopicTypeInformation> topicTypeInformations() const
{
return m_topicTypeInfos;
}
bool isExternalType() const
{
return !service.isEmpty();
}
CompleteStructInformation structInformationByTableName(const QString &tableName) const;
bool isSequence() const
{
return bIsSequence;
}
EnumInformation enumInformationByType(const QString &type, bool checkExternals = true, bool verbose = true);
QString fqType() const
{
return service + QStringLiteral("::") + type;
}
};
CompleteTopicTypeInformation topicTypeInformationByStructType(const QString &type, bool checkExternals = true);
CompleteTopicTypeInformation externalTopicTypeByStructType(const ServiceTypeStruct &sts);
explicit StructBuilder(XmlReader* xmlReader);
~StructBuilder() = default;
QVector<EnumInformation> enumInformations() const
{
return m_enumInfos;
}
bool buildStructures();
QMap<QString, CompleteTableInformation> getDbTables() const
{
return m_sqlTableInformations;
}
QVector<CompleteStructInformation> structInformations() const
{
return m_structInfos;
}
QMap<QString, ViewInformation> getDbViews() const
{
return m_sqlViewInformations;
}
QVector<CompleteTopicTypeInformation> topicTypeInformations() const
{
return m_topicTypeInfos;
}
bool needPoint3d() const
{
return m_needPoint3d;
}
CompleteStructInformation structInformationByTableName(const QString& tableName) const;
bool needPgArrayInclude() const
{
return m_needPgArrayInclude;
}
EnumInformation enumInformationByType(const QString& type, bool checkExternals = true, bool verbose = true);
CompleteTableInformation completeTableInformation(const CompleteTopicTypeInformation &ctti);
CompleteTableInformation getRecordingTopicTable(const QString &structName);
QMap<QString, CompleteTableInformation> getRecordingTopicTables();
QVector<QSharedPointer<DataTypeInfo> > getSerializeFromToJsonTopics() const;
bool fixupQVariantConversions(MemberInformation &mi) const;
CompleteTopicTypeInformation topicTypeInformationByStructType(const QString& type, bool checkExternals = true);
CompleteTopicTypeInformation externalTopicTypeByStructType(const ServiceTypeStruct& sts);
Q_REQUIRED_RESULT static QString firstCharLowercase(const QString &txt);
Q_REQUIRED_RESULT static QString camelCaseString(const QString &in, bool bFirstUppercase = false);
Q_REQUIRED_RESULT static QString camelCaseToUnderline(const QString &in);
QVector<EnumInformation> enumInformations() const
{
return m_enumInfos;
}
bool buildJSonStructureInformationFromIdlData(const CompleteTopicTypeInformation &ctti);
QMap<QString, QVector<MemberInformation>> jsonStructureInformation() const { return m_jsonStructureInformation; }
QMap<QString, CompleteTableInformation> getDbTables() const
{
return m_sqlTableInformations;
}
private:
bool handleEnum(const EnumInformation &ei);
bool handleTable(const ServiceStructInformation &ssi);
bool handleIdlStructInfo(const TopicTypeInformation &tti,
QVector<CompleteTopicTypeInformation> &destination,
const QString &svcName = QString());
bool loadExternalTopicType(const ServiceTypeStruct &sts);
QMap<QString, ViewInformation> getDbViews() const
{
return m_sqlViewInformations;
}
bool getColumnsFromTable(const QString &tableName,
QVector<ColumnInformationEx> &columns,
QVector<QString> &tableNames) const;
bool needPoint3d() const
{
return m_needPoint3d;
}
bool fixupCustomDbDatatypes(MemberInformation &memberInfo, QVector<MemberInformation> &members);
bool fixupDatatypePoint2d(MemberInformation &memberInfo, QVector<MemberInformation> &members);
bool fixupDatatypePoint3d(MemberInformation &memberInfo, QVector<MemberInformation> &members);
bool fixupDatatypeIntegerArray(MemberInformation &memberInfo);
bool needPgArrayInclude() const
{
return m_needPgArrayInclude;
}
QVector<MemberInformation> buildDbTableInformationFromIdlData(const CompleteTopicTypeInformation &ctti,
const QString &tableName,
const QString &columnNamePrefix,
const QString &cppStructure);
void addToSerializeFromToJsonTopics(const QSharedPointer<DataTypeInfo> &toAdd);
CompleteTableInformation getRecordingTopicTable(const CompleteTopicTypeInformation &ctti,
const MemberInformation &miPrimaryKey);
MemberInformation getRecordPrimaryKey() const;
CompleteTableInformation completeTableInformation(const CompleteTopicTypeInformation& ctti);
CompleteTableInformation getRecordingTopicTable(const QString& structName);
QMap<QString, CompleteTableInformation> getRecordingTopicTables();
QVector<QSharedPointer<DataTypeInfo>> getSerializeFromToJsonTopics() const;
bool fixupQVariantConversions(MemberInformation& mi) const;
ServiceTypeStruct extractServiceAndTypeFromTypename(const QString &type);
Q_REQUIRED_RESULT static QString firstCharLowercase(const QString& txt);
Q_REQUIRED_RESULT static QString camelCaseString(const QString& in, bool bFirstUppercase = false);
Q_REQUIRED_RESULT static QString camelCaseToUnderline(const QString& in);
void addToSqlTableInformation(const MemberInformation &mi);
private:
QVector<CompleteStructInformation> m_structInfos;
QVector<CompleteTopicTypeInformation> m_topicTypeInfos;
mutable QVector<CompleteTopicTypeInformation> m_externalTopicTypes;
QVector<EnumInformation> m_enumInfos;
QMap<QString, CompleteTableInformation> m_sqlTableInformations;
QMap<QString, ViewInformation> m_sqlViewInformations;
QSet<QString> m_sqlTableInformationsAlreadyAvailable;
QVector<QSharedPointer<DataTypeInfo>> m_serializeFromToJsonTopics;
bool buildJSonStructureInformationFromIdlData(const CompleteTopicTypeInformation& ctti);
QMap<QString, QVector<MemberInformation>> m_jsonStructureInformation;
QMap<QString, QVector<MemberInformation>> jsonStructureInformation() const
{
return m_jsonStructureInformation;
}
bool m_needPoint3d;
bool m_needPgArrayInclude;
private:
bool handleEnum(const EnumInformation& ei);
bool handleTable(const ServiceStructInformation& ssi);
bool handleIdlStructInfo(const TopicTypeInformation& tti, QVector<CompleteTopicTypeInformation>& destination,
const QString& svcName = QString());
bool loadExternalTopicType(const ServiceTypeStruct& sts);
XmlReader *m_xmlReader;
NGL::INGLLogger &m_logger;
NGL::INGLLogger &m_loggerCSV;
bool getColumnsFromTable(const QString& tableName, QVector<ColumnInformationEx>& columns,
QVector<QString>& tableNames) const;
bool fixupCustomDbDatatypes(MemberInformation& memberInfo, QVector<MemberInformation>& members);
bool fixupDatatypePoint2d(MemberInformation& memberInfo, QVector<MemberInformation>& members);
bool fixupDatatypePoint3d(MemberInformation& memberInfo, QVector<MemberInformation>& members);
bool fixupDatatypeIntegerArray(MemberInformation& memberInfo);
QVector<MemberInformation> buildDbTableInformationFromIdlData(const CompleteTopicTypeInformation& ctti,
const QString& tableName,
const QString& columnNamePrefix,
const QString& cppStructure);
void addToSerializeFromToJsonTopics(const QSharedPointer<DataTypeInfo>& toAdd);
CompleteTableInformation getRecordingTopicTable(const CompleteTopicTypeInformation& ctti,
const MemberInformation& miPrimaryKey);
MemberInformation getRecordPrimaryKey() const;
ServiceTypeStruct extractServiceAndTypeFromTypename(const QString& type);
void addToSqlTableInformation(const MemberInformation& mi);
private:
QVector<CompleteStructInformation> m_structInfos;
QVector<CompleteTopicTypeInformation> m_topicTypeInfos;
mutable QVector<CompleteTopicTypeInformation> m_externalTopicTypes;
QVector<EnumInformation> m_enumInfos;
QMap<QString, CompleteTableInformation> m_sqlTableInformations;
QMap<QString, ViewInformation> m_sqlViewInformations;
QSet<QString> m_sqlTableInformationsAlreadyAvailable;
QVector<QSharedPointer<DataTypeInfo>> m_serializeFromToJsonTopics;
QMap<QString, QVector<MemberInformation>> m_jsonStructureInformation;
bool m_needPoint3d;
bool m_needPgArrayInclude;
XmlReader* m_xmlReader;
NGL::INGLLogger& m_logger;
NGL::INGLLogger& m_loggerCSV;
};
}
} // namespace CodeGen
File diff suppressed because it is too large. Load diff
+324 -304
View File
@@ -31,409 +31,429 @@ class QDomElement;
namespace CodeGen
{
enum ExerciseDependency
{
Undefined = 0,
Global = 0x1,
Exercise = 0x2,
GlobalAndExercise = 0x3
};
enum ExerciseDependency { Undefined = 0, Global = 0x1, Exercise = 0x2, GlobalAndExercise = 0x3 };
struct EnumKeyValuePair
{
QString key;
int value = 0;
QString key;
int value = 0;
};
struct EnumInformation
{
QString enumName;
QString tableName;
QString serviceName;
QVector<EnumKeyValuePair> values;
QString enumName;
QString tableName;
QString serviceName;
QVector<EnumKeyValuePair> values;
bool isValid() const { return !enumName.isEmpty(); }
bool isValid() const
{
return !enumName.isEmpty();
}
};
struct ColumnInformation
{
QString columnName;
QString datatype;
QString comment;
QString defaultValue;
bool isPrimaryKey = false;
bool isAssignmentForPrimaryTablePk = false;
bool isForeignKey = false;
bool generateSelectRemove = false;
bool canBeNull = true;
bool hasSequence = false;
bool isOptional = false;
int sequenceStart = 0;
int sequenceIncrement = 0;
QString columnName;
QString datatype;
QString comment;
QString defaultValue;
bool isPrimaryKey = false;
bool isAssignmentForPrimaryTablePk = false;
bool isForeignKey = false;
bool generateSelectRemove = false;
bool canBeNull = true;
bool hasSequence = false;
bool isOptional = false;
int sequenceStart = 0;
int sequenceIncrement = 0;
};
struct IdlColumnInformation
{
QString name;
QString type;
QString comment;
bool isKey = false;
bool isOptional = false;
bool isTranslatable = false;
QString name;
QString type;
QString comment;
bool isKey = false;
bool isOptional = false;
bool isTranslatable = false;
};
struct ForeignKeyInformation
{
struct Endpoint
{
QString service;
QString serviceAbbr;
QString schema;
QString tableName;
QString columnName;
};
struct Endpoint
{
QString service;
QString serviceAbbr;
QString schema;
QString tableName;
QString columnName;
};
QString name;
Endpoint source;
Endpoint destination;
enum class OnDeleteAction
{
NoAction,
Cascade,
Restrict,
SetNull,
SetDefault
} deleteAction = OnDeleteAction::Cascade;
QString name;
Endpoint source;
Endpoint destination;
enum class OnDeleteAction {
NoAction,
Cascade,
Restrict,
SetNull,
SetDefault
} deleteAction = OnDeleteAction::Cascade;
};
struct CustomServiceFunctionInformation
{
QString methodName;
QString returnValue;
QString signature;
bool isConst = false;
QVector<QString> paramTypes;
QVector<QString> paramNames;
enum class Type
{
Db,
DbNotify,
Dtc
} type = Type::Db;
QString methodName;
QString returnValue;
QString signature;
bool isConst = false;
QVector<QString> paramTypes;
QVector<QString> paramNames;
enum class Type { Db, DbNotify, Dtc } type = Type::Db;
};
struct DbNotifcationInformation : public CustomServiceFunctionInformation
{
DbNotifcationInformation() = default;
explicit DbNotifcationInformation(const CustomServiceFunctionInformation &d)
: CustomServiceFunctionInformation(d)
{}
enum class NotificationType
{
BeforeInsert,
AfterInsert,
BeforeUpdate,
AfterUpdate,
BeforeDelete,
AfterDelete
};
QVector<NotificationType> notificationType;
DbNotifcationInformation() = default;
explicit DbNotifcationInformation(const CustomServiceFunctionInformation& d) : CustomServiceFunctionInformation(d)
{
}
enum class NotificationType { BeforeInsert, AfterInsert, BeforeUpdate, AfterUpdate, BeforeDelete, AfterDelete };
QVector<NotificationType> notificationType;
};
struct ConstraintInformation
{
enum struct Type
{
unknown = 0x00,
unique = 0x01,
index = 0x02
} type = Type::unknown;
QString name;
QStringList affectedColumns;
enum struct Type { unknown = 0x00, unique = 0x01, index = 0x02 } type = Type::unknown;
QString name;
QStringList affectedColumns;
};
struct TableInformation
{
QString name;
QString structName;
QString comment;
QVector<ColumnInformation> plainColumns;
QVector<QSharedPointer<ForeignKeyInformation> > foreignKeys;
QVector<ConstraintInformation> constraints;
ExerciseDependency exerciseDependency = ExerciseDependency::Undefined;
QString name;
QString structName;
QString comment;
QVector<ColumnInformation> plainColumns;
QVector<QSharedPointer<ForeignKeyInformation>> foreignKeys;
QVector<ConstraintInformation> constraints;
ExerciseDependency exerciseDependency = ExerciseDependency::Undefined;
QSharedPointer<ForeignKeyInformation> fkInformationForColumn(const QString &tableName,
const QString &columnName) const
{
for (const QSharedPointer<ForeignKeyInformation> &fki : foreignKeys)
QSharedPointer<ForeignKeyInformation> fkInformationForColumn(const QString& tableName,
const QString& columnName) const
{
if (fki->source.columnName == columnName &&
fki->source.tableName == tableName)
return fki;
for (const QSharedPointer<ForeignKeyInformation>& fki : foreignKeys)
{
if (fki->source.columnName == columnName && fki->source.tableName == tableName)
return fki;
}
return QSharedPointer<ForeignKeyInformation>();
}
return QSharedPointer<ForeignKeyInformation>();
}
};
struct ViewInformation
{
QString name;
QString comment;
QString structName;
QString baseTable;
QString baseSchema;
QString filter;
ExerciseDependency exerciseDependency = ExerciseDependency::Undefined;
QString name;
QString comment;
QString structName;
QString baseTable;
QString baseSchema;
QString filter;
ExerciseDependency exerciseDependency = ExerciseDependency::Undefined;
};
struct ServiceStructInformation
{
QString name;
QString primaryTable;
bool hasStaticContent = false;
QString name;
QString primaryTable;
bool hasStaticContent = false;
bool operator<(const ServiceStructInformation &o) const
{
if (hasStaticContent != o.hasStaticContent)
return hasStaticContent < o.hasStaticContent;
if (name != o.name)
return name < o.name;
return primaryTable < o.primaryTable;
}
QVector<DbNotifcationInformation> dbNotifications;
bool operator<(const ServiceStructInformation& o) const
{
if (hasStaticContent != o.hasStaticContent)
return hasStaticContent < o.hasStaticContent;
if (name != o.name)
return name < o.name;
return primaryTable < o.primaryTable;
}
QVector<DbNotifcationInformation> dbNotifications;
};
struct TopicTypeInformationBase
{
TopicTypeInformationBase() = default;
virtual ~TopicTypeInformationBase() = default;
TopicTypeInformationBase() = default;
virtual ~TopicTypeInformationBase() = default;
QString name;
QString baseValueType;
QString comment;
bool isDataObject = false;
bool dtsAutogen = true;
bool dtcAutogen = true;
bool recordTopic = false;
bool routeToClient = true;
bool routeToServer = false;
bool routeInReplay = true;
bool autosubscribe = true;
QString name;
QString baseValueType;
QString comment;
bool isDataObject = false;
bool dtsAutogen = true;
bool dtcAutogen = true;
bool recordTopic = false;
bool routeToClient = true;
bool routeToServer = false;
bool routeInReplay = true;
bool autosubscribe = true;
#ifdef RTI_DDS_AVAILABLE
dds::core::xtypes::ExtensibilityKind extensibility = dds::core::xtypes::ExtensibilityKind::EXTENSIBLE;
dds::core::xtypes::ExtensibilityKind extensibility = dds::core::xtypes::ExtensibilityKind::EXTENSIBLE;
#else
int extensibility = 0; // Placeholder when RTI DDS is not available
int extensibility = 0; // Placeholder when RTI DDS is not available
#endif
virtual bool isValid() const { return !name.isEmpty(); }
virtual bool isValid() const
{
return !name.isEmpty();
}
bool operator<(const TopicTypeInformationBase &o) const
{
if (name != o.name)
return name < o.name;
return baseValueType < o.baseValueType;
}
bool operator<(const TopicTypeInformationBase& o) const
{
if (name != o.name)
return name < o.name;
return baseValueType < o.baseValueType;
}
};
struct TopicTypeInformation : public TopicTypeInformationBase
{
QVector<IdlColumnInformation> columns;
QVector<IdlColumnInformation> columns;
};
struct FunctionTopic
{
QString name;
QString requestTopicType;
QString replyTopicType;
QString requestTopicName;
QString replyTopicName;
bool routeInReplay = false;
QString name;
QString requestTopicType;
QString replyTopicType;
QString requestTopicName;
QString replyTopicName;
bool routeInReplay = false;
};
class CODEGEN_BASE_EXPORT XmlReader final
{
public:
XmlReader();
public:
XmlReader();
bool readServiceFile(const QString &svcFile,
const QString &idlServiceInfoFile = QString(),
const XmlReader *parent = nullptr);
QString errorString() const
{
return m_errorString;
}
bool readServiceFile(const QString& svcFile, const QString& idlServiceInfoFile = QString(),
const XmlReader* parent = nullptr);
QString getServiceNamespace() const { return m_svcNamespace; }
QString getServiceAbbr() const { return m_svcAbbr; }
QStringList getGroupNames() const { return m_groupNames; }
int getPrio() const { return m_prio;}
QStringList getProcNames() const { return m_svcProcNames; }
bool hasCustomRecordReplayPlugin() const { return m_customRecordReplay; }
bool getDevMode() const { return m_svcDevMode; }
bool isServiceExerciseIndependent() const { return m_exerciseDependency == ExerciseDependency::Global; }
ExerciseDependency defaultExerciseDependency() const { return m_exerciseDependency; }
QMap<QString, QVector<QString> > getDbClass2TableMapping() const { return m_dbClassTables; }
QMap<QString, QString> getStruct2BaseClassRelations() const { return m_struct2BaseClass; }
QVector<ServiceStructInformation> getStructToGenerate() const { return m_structsToGenerate; }
QMap<QString, TopicTypeInformation > getIdlStructInformation() const { return m_idlStructsToGenerate; }
QVector<TopicTypeInformation> getIdlStructToGenerate() const
{
QVector<TopicTypeInformation> res;
res.reserve(m_idlStructsToGenerate.size());
auto it = m_idlStructsToGenerate.constBegin();
while (it != m_idlStructsToGenerate.constEnd())
QString errorString() const
{
res.append(it.value());
++it;
return m_errorString;
}
return res;
}
QMap<QString, QSharedPointer<TableInformation> > getTables() const
{
return m_tables;
}
QMap<QString, QSharedPointer<ViewInformation> > getViews() const
{
return m_views;
}
QSharedPointer<TableInformation> getTable(const QString &table) const
{
return m_tables.value(table);
}
QVector<EnumInformation> getEnumerations() const
{
return m_enumerations;
}
QVector<IdlColumnInformation> getIdlColumns(const QString &structName) const
{
return m_idlStructsToGenerate.value(structName).columns;
}
QString getServiceNamespace() const
{
return m_svcNamespace;
}
QVector<FunctionTopic> getFunctionTopics() const
{
return m_functionTopics;
}
QVector<TopicTypeInformation> getExternalTopicTypes() const
{
return m_externalTopicTypes;
}
QString getServiceAbbr() const
{
return m_svcAbbr;
}
QString idlFileForService(const QString &serviceName) const
{
return getIdlFileForService(m_idlFiles, serviceName);
}
QStringList getGroupNames() const
{
return m_groupNames;
}
QString xmlFileForService(const QString &serviceName) const
{
return getIdlFileForService(m_xmlFiles, serviceName);
}
int getPrio() const
{
return m_prio;
}
QMap<QString, bool> usedServices() const
{
return m_usedServices;
}
QStringList getProcNames() const
{
return m_svcProcNames;
}
QVector<CustomServiceFunctionInformation> getCustomFunctions() const
{
return m_customFunctions;
}
bool hasCustomRecordReplayPlugin() const
{
return m_customRecordReplay;
}
bool getDevMode() const
{
return m_svcDevMode;
}
TopicTypeInformation loadExternalTopicType(const QString &externalServiceName, const QString &topicTypeName);
EnumInformation getExternalEnumeration(const QString &externalServiceName, const QString &enumName, bool verbose);
bool isServiceExerciseIndependent() const
{
return m_exerciseDependency == ExerciseDependency::Global;
}
static ExerciseDependency string2ExerciseDependency(const QString &str);
ExerciseDependency defaultExerciseDependency() const
{
return m_exerciseDependency;
}
XmlReader(const XmlReader &) = delete;
XmlReader &operator=(const XmlReader &) = delete;
QMap<QString, QVector<QString>> getDbClass2TableMapping() const
{
return m_dbClassTables;
}
private:
NGL::INGLLogger &m_logger;
void parseDBSserviceStructs(const QDomElement &rootElement);
void parseDBTables(const QDomElement &rootElement);
void parseDBViews(const QDomElement &rootElement);
void parseEnumerations(const QDomElement &rootElement);
void parseTopicTypes(const QDomElement &rootElement);
void parseFunctionTopics(const QDomElement &rootElement);
void parseCustomDtcFunctions(const QDomElement &rootElement);
QMap<QString, QString> getStruct2BaseClassRelations() const
{
return m_struct2BaseClass;
}
static QString getAttribute(const QDomElement &element,
const QString &attributeName,
bool bOptional = false);
static bool getAttributeBool(const QDomElement &element,
const QString &attributeName,
bool bOptional, bool defaultValue);
static int getAttributeInt(const QDomElement &element,
const QString &attributeName,
bool bOptional = false, int defaultValue = 0);
QVector<ServiceStructInformation> getStructToGenerate() const
{
return m_structsToGenerate;
}
ColumnInformation parseTableColumn(const QDomElement &column, const QString &tableName) const;
IdlColumnInformation parseIdlStructColumn(const QDomElement &column) const;
QMap<QString, TopicTypeInformation> getIdlStructInformation() const
{
return m_idlStructsToGenerate;
}
QSharedPointer<ForeignKeyInformation> parseForeignKey(const QDomElement &foreignKey) const;
ForeignKeyInformation::Endpoint parseForeignKeyEndpoint(const QString &foreignKeyName,
const QDomElement &endpoint) const;
ConstraintInformation parseConstraint(const QDomElement &constraint) const;
CustomServiceFunctionInformation parseCustomFunction(const QDomElement &customFunc, CustomServiceFunctionInformation::Type funcType) const;
DbNotifcationInformation parseDbNotification(const QDomElement &customFunc) const;
bool loadExternalService(const QString &serviceName);
void loadIdlInfofile(const QString &idlServiceInfoFile);
QString getIdlFileForService(const QMap<QString, QString> &data, const QString &serviceName) const;
QString serviceNameAbbreviation(const QString &serviceName) const;
void getServiceNameInfoFromFilePath(const QStringList &parts);
static QString serviceNamespaceFromFile(const QString &fn);
QVector<TopicTypeInformation> getIdlStructToGenerate() const
{
QVector<TopicTypeInformation> res;
res.reserve(m_idlStructsToGenerate.size());
auto it = m_idlStructsToGenerate.constBegin();
while (it != m_idlStructsToGenerate.constEnd())
{
res.append(it.value());
++it;
}
return res;
}
QString m_svcNamespace;
QString m_svcAbbr;
QStringList m_svcProcNames;
bool m_customRecordReplay;
QMap<QString, QSharedPointer<TableInformation>> getTables() const
{
return m_tables;
}
ExerciseDependency m_exerciseDependency{ExerciseDependency::Exercise};
QMap<QString, QSharedPointer<ViewInformation>> getViews() const
{
return m_views;
}
QMap<QString, QVector<QString> > m_dbClassTables;
QSharedPointer<TableInformation> getTable(const QString& table) const
{
return m_tables.value(table);
}
QMap<QString, QString> m_struct2BaseClass;
QVector<ServiceStructInformation> m_structsToGenerate;
QVector<EnumInformation> getEnumerations() const
{
return m_enumerations;
}
QMap<QString, TopicTypeInformation> m_idlStructsToGenerate;
QVector<IdlColumnInformation> getIdlColumns(const QString& structName) const
{
return m_idlStructsToGenerate.value(structName).columns;
}
QVector<FunctionTopic> m_functionTopics;
QVector<TopicTypeInformation> m_externalTopicTypes;
QVector<CustomServiceFunctionInformation> m_customFunctions;
QVector<FunctionTopic> getFunctionTopics() const
{
return m_functionTopics;
}
QVector<TopicTypeInformation> getExternalTopicTypes() const
{
return m_externalTopicTypes;
}
QMap<QString, QSharedPointer<TableInformation> > m_tables;
QMap<QString, QSharedPointer<ViewInformation> > m_views;
QVector<EnumInformation> m_enumerations;
QString m_errorString;
QString idlFileForService(const QString& serviceName) const
{
return getIdlFileForService(m_idlFiles, serviceName);
}
QString xmlFileForService(const QString& serviceName) const
{
return getIdlFileForService(m_xmlFiles, serviceName);
}
QMap<QString, QSharedPointer<XmlReader> > m_externalXmlInformations;
QMap<QString, QString> m_idlFiles;
QMap<QString, QString> m_xmlFiles;
QMap<QString, bool> m_usedServices;
QMap<QString, QString> m_fullServiceName2Abbreviation;
QMap<QString, bool> usedServices() const
{
return m_usedServices;
}
QStringList m_groupNames;
int m_prio;
bool m_svcDevMode{false};
QVector<CustomServiceFunctionInformation> getCustomFunctions() const
{
return m_customFunctions;
}
TopicTypeInformation loadExternalTopicType(const QString& externalServiceName, const QString& topicTypeName);
EnumInformation getExternalEnumeration(const QString& externalServiceName, const QString& enumName, bool verbose);
static ExerciseDependency string2ExerciseDependency(const QString& str);
XmlReader(const XmlReader&) = delete;
XmlReader& operator=(const XmlReader&) = delete;
private:
NGL::INGLLogger& m_logger;
void parseDBSserviceStructs(const QDomElement& rootElement);
void parseDBTables(const QDomElement& rootElement);
void parseDBViews(const QDomElement& rootElement);
void parseEnumerations(const QDomElement& rootElement);
void parseTopicTypes(const QDomElement& rootElement);
void parseFunctionTopics(const QDomElement& rootElement);
void parseCustomDtcFunctions(const QDomElement& rootElement);
static QString getAttribute(const QDomElement& element, const QString& attributeName, bool bOptional = false);
static bool getAttributeBool(const QDomElement& element, const QString& attributeName, bool bOptional,
bool defaultValue);
static int getAttributeInt(const QDomElement& element, const QString& attributeName, bool bOptional = false,
int defaultValue = 0);
ColumnInformation parseTableColumn(const QDomElement& column, const QString& tableName) const;
IdlColumnInformation parseIdlStructColumn(const QDomElement& column) const;
QSharedPointer<ForeignKeyInformation> parseForeignKey(const QDomElement& foreignKey) const;
ForeignKeyInformation::Endpoint parseForeignKeyEndpoint(const QString& foreignKeyName,
const QDomElement& endpoint) const;
ConstraintInformation parseConstraint(const QDomElement& constraint) const;
CustomServiceFunctionInformation parseCustomFunction(const QDomElement& customFunc,
CustomServiceFunctionInformation::Type funcType) const;
DbNotifcationInformation parseDbNotification(const QDomElement& customFunc) const;
bool loadExternalService(const QString& serviceName);
void loadIdlInfofile(const QString& idlServiceInfoFile);
QString getIdlFileForService(const QMap<QString, QString>& data, const QString& serviceName) const;
QString serviceNameAbbreviation(const QString& serviceName) const;
void getServiceNameInfoFromFilePath(const QStringList& parts);
static QString serviceNamespaceFromFile(const QString& fn);
QString m_svcNamespace;
QString m_svcAbbr;
QStringList m_svcProcNames;
bool m_customRecordReplay;
ExerciseDependency m_exerciseDependency{ExerciseDependency::Exercise};
QMap<QString, QVector<QString>> m_dbClassTables;
QMap<QString, QString> m_struct2BaseClass;
QVector<ServiceStructInformation> m_structsToGenerate;
QMap<QString, TopicTypeInformation> m_idlStructsToGenerate;
QVector<FunctionTopic> m_functionTopics;
QVector<TopicTypeInformation> m_externalTopicTypes;
QVector<CustomServiceFunctionInformation> m_customFunctions;
QMap<QString, QSharedPointer<TableInformation>> m_tables;
QMap<QString, QSharedPointer<ViewInformation>> m_views;
QVector<EnumInformation> m_enumerations;
QString m_errorString;
QMap<QString, QSharedPointer<XmlReader>> m_externalXmlInformations;
QMap<QString, QString> m_idlFiles;
QMap<QString, QString> m_xmlFiles;
QMap<QString, bool> m_usedServices;
QMap<QString, QString> m_fullServiceName2Abbreviation;
QStringList m_groupNames;
int m_prio;
bool m_svcDevMode{false};
};
}
} // namespace CodeGen
+9 -9
View File
@@ -5,13 +5,13 @@
#include <QtCore/qglobal.h>
#ifndef CODEGEN_BASE_EXPORT
# ifdef BUILD_STATIC_LIBRARIES
# define CODEGEN_BASE_EXPORT
# else
# if defined(MAKE_CODEGEN_BASE_LIB)
# define CODEGEN_BASE_EXPORT Q_DECL_EXPORT
# else
# define CODEGEN_BASE_EXPORT Q_DECL_IMPORT
# endif
# endif
#ifdef BUILD_STATIC_LIBRARIES
#define CODEGEN_BASE_EXPORT
#else
#if defined(MAKE_CODEGEN_BASE_LIB)
#define CODEGEN_BASE_EXPORT Q_DECL_EXPORT
#else
#define CODEGEN_BASE_EXPORT Q_DECL_IMPORT
#endif
#endif
#endif
+138 -143
View File
@@ -1,172 +1,167 @@
#include "StructBuilder.h"
#include "XmlReader.h"
#include "CppTopicGeneratorGrantlee.h"
#include "DaoGeneratorGrantlee.h"
#include "DatabaseGeneratorGrantlee.h"
#include "CppTopicGeneratorGrantlee.h"
#include "SqlGenerator.h"
#include "StructBuilder.h"
#include "XmlReader.h"
#include <nglapplication/nglcoreapplication.h>
#include <QDir>
#include <NGLLogger/INGLLogger.h>
#include <LtsCommandLineParser/LtsCommandLineParser.h>
#include <NGLLogger/INGLLogger.h>
#include <QDir>
#include <nglapplication/nglcoreapplication.h>
class CmdLineParser : public LtsCommandLineParser::LtsCommandLineParser
{
public:
CmdLineParser()
: LtsCommandLineParser(LtsCommandLineParser::LtsCommandLineParser::None)
{
addOption({ QStringList() << QStringLiteral("s") << QStringLiteral("servicefile"),
QStringLiteral("full path to the service xml-file"),
QStringLiteral("service xml-file"),
QStringLiteral("/home")
});
addOption({ QStringList() << QStringLiteral("a") << QStringLiteral("action"),
QStringLiteral("the action to execute"),
QStringLiteral("DATABASE|DATABASE_SERVER|IDL|DDS_TOPICS"),
QStringLiteral("/0")
});
addOption({ QStringList() << QStringLiteral("o") << QStringLiteral("outdir"),
QStringLiteral("the output directory where to put the generated files"),
QStringLiteral("output directory"),
QStringLiteral("/home")
});
addOption({ QStringList() << QStringLiteral("i") << QStringLiteral("idlinfo"),
QStringLiteral("the info file with all available idl service files"),
QStringLiteral("info file for idl"),
QStringLiteral("/0")
});
}
bool init()
{
if (!LtsCommandLineParser::init())
return false;
if (serviceFile().isEmpty() || action().isEmpty() || outDir().isEmpty())
public:
CmdLineParser() : LtsCommandLineParser(LtsCommandLineParser::LtsCommandLineParser::None)
{
showHelp();
return false;
}
return true;
}
addOption({QStringList() << QStringLiteral("s") << QStringLiteral("servicefile"),
QStringLiteral("full path to the service xml-file"), QStringLiteral("service xml-file"),
QStringLiteral("/home")});
QString serviceFile() const { return value(QStringLiteral("s")); }
QString action() const { return value(QStringLiteral("a")); }
QString outDir() const { return value(QStringLiteral("o")); }
QString idlInfoFile() const { return value(QStringLiteral("i")); }
addOption({QStringList() << QStringLiteral("a") << QStringLiteral("action"),
QStringLiteral("the action to execute"), QStringLiteral("DATABASE|DATABASE_SERVER|IDL|DDS_TOPICS"),
QStringLiteral("/0")});
addOption({QStringList() << QStringLiteral("o") << QStringLiteral("outdir"),
QStringLiteral("the output directory where to put the generated files"),
QStringLiteral("output directory"), QStringLiteral("/home")});
addOption({QStringList() << QStringLiteral("i") << QStringLiteral("idlinfo"),
QStringLiteral("the info file with all available idl service files"),
QStringLiteral("info file for idl"), QStringLiteral("/0")});
}
bool init()
{
if (!LtsCommandLineParser::init())
return false;
if (serviceFile().isEmpty() || action().isEmpty() || outDir().isEmpty())
{
showHelp();
return false;
}
return true;
}
QString serviceFile() const
{
return value(QStringLiteral("s"));
}
QString action() const
{
return value(QStringLiteral("a"));
}
QString outDir() const
{
return value(QStringLiteral("o"));
}
QString idlInfoFile() const
{
return value(QStringLiteral("i"));
}
};
int main(int argc, char **argv)
int main(int argc, char** argv)
{
NGLCoreApplication app(argc, argv);
app.createLogger("CodeGen", "codegen_log4cxx.props", true );
NGLCoreApplication app(argc, argv);
app.createLogger("CodeGen", "codegen_log4cxx.props", true);
NGL::INGLLogger &m_logger = app.baseLogger();
NGL::INGLLogger& m_logger = app.baseLogger();
CmdLineParser options;
if (!options.init())
return -1;
CmdLineParser options;
if (!options.init())
return -1;
QScopedPointer<CodeGen::XmlReader> reader(new CodeGen::XmlReader);
QScopedPointer<CodeGen::XmlReader> reader(new CodeGen::XmlReader);
DEBUG_LOG(m_logger) << "ServiceFile: " << options.serviceFile();
DEBUG_LOG(m_logger) << "IdlInfoFile: " << options.idlInfoFile();
if (!reader->readServiceFile(options.serviceFile(), options.idlInfoFile()))
{
ERROR_LOG(m_logger) << "Error parsing service file '" << options.serviceFile()
<< ": " << reader->errorString();
return 2;
}
QDir dir(options.outDir());
DEBUG_LOG(m_logger) << "Directory: " << options.outDir();
if (!dir.exists() && !dir.mkpath(options.outDir()))
{
ERROR_LOG(m_logger) << "Directory '" << options.outDir()
<< "' does not exist and can not be created!";
return 3;
}
QScopedPointer<CodeGen::StructBuilder> structBuilder(new CodeGen::StructBuilder(reader.data()));
if (!structBuilder->buildStructures())
{
ERROR_LOG(m_logger) << "Error building up structures";
return 4;
}
const QString action = options.action().toLower();
QScopedPointer<CodeGen::GeneratorGrantleeBase> generator;
if (action == QStringLiteral("dao"))
generator.reset(new CodeGen::DaoGeneratorGrantlee);
else if (action == QStringLiteral("database"))
generator.reset(new CodeGen::DatabaseGeneratorGrantlee(false));
else if (action == QStringLiteral("database_server"))
generator.reset(new CodeGen::DatabaseGeneratorGrantlee(true));
else if (action == QStringLiteral("dds_topics"))
generator.reset(new CodeGen::CppTopicGeneratorGrantlee);
else if (action == QStringLiteral("sql"))
{
CodeGen::SqlGenerator sql(reader.data(), structBuilder.data());
if (!sql.generateData(35))
return 8;
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise))
DEBUG_LOG(m_logger) << "ServiceFile: " << options.serviceFile();
DEBUG_LOG(m_logger) << "IdlInfoFile: " << options.idlInfoFile();
if (!reader->readServiceFile(options.serviceFile(), options.idlInfoFile()))
{
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr();
return 10;
ERROR_LOG(m_logger) << "Error parsing service file '" << options.serviceFile() << ": " << reader->errorString();
return 2;
}
if (!sql.generateData(42))
return 8;
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise))
QDir dir(options.outDir());
DEBUG_LOG(m_logger) << "Directory: " << options.outDir();
if (!dir.exists() && !dir.mkpath(options.outDir()))
{
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr();
return 10;
ERROR_LOG(m_logger) << "Directory '" << options.outDir() << "' does not exist and can not be created!";
return 3;
}
sql.generateData(0);
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Global))
QScopedPointer<CodeGen::StructBuilder> structBuilder(new CodeGen::StructBuilder(reader.data()));
if (!structBuilder->buildStructures())
{
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr();
return 10;
ERROR_LOG(m_logger) << "Error building up structures";
return 4;
}
const QString action = options.action().toLower();
QScopedPointer<CodeGen::GeneratorGrantleeBase> generator;
if (action == QStringLiteral("dao"))
generator.reset(new CodeGen::DaoGeneratorGrantlee);
else if (action == QStringLiteral("database"))
generator.reset(new CodeGen::DatabaseGeneratorGrantlee(false));
else if (action == QStringLiteral("database_server"))
generator.reset(new CodeGen::DatabaseGeneratorGrantlee(true));
else if (action == QStringLiteral("dds_topics"))
generator.reset(new CodeGen::CppTopicGeneratorGrantlee);
else if (action == QStringLiteral("sql"))
{
CodeGen::SqlGenerator sql(reader.data(), structBuilder.data());
if (!sql.generateData(35))
return 8;
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise))
{
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr();
return 10;
}
if (!sql.generateData(42))
return 8;
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise))
{
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr();
return 10;
}
sql.generateData(0);
if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Global))
{
ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr();
return 10;
}
return 0;
}
else
{
ERROR_LOG(m_logger) << "Invalid action '" << options.action() << "' given!";
return 5;
}
if (!generator->init(reader.data(), structBuilder.data()))
{
ERROR_LOG(m_logger) << "Error initializing generator!";
return 6;
}
const auto posArgs = options.positionalArguments();
for (const QString& file : posArgs)
{
if (!generator->generateData(file, dir.absolutePath()))
return 7;
}
return 0;
}
else
{
ERROR_LOG(m_logger) << "Invalid action '" << options.action() << "' given!";
return 5;
}
if (!generator->init(reader.data(), structBuilder.data()))
{
ERROR_LOG(m_logger) << "Error initializing generator!";
return 6;
}
const auto posArgs = options.positionalArguments();
for (const QString &file : posArgs)
{
if (!generator->generateData(file, dir.absolutePath()))
return 7;
}
return 0;
}
+99 -109
View File
@@ -1,158 +1,148 @@
#include "main_grantlee_gui.h"
#include "ui_main_grantlee_gui.h"
#include "StructBuilder.h"
#include "XmlReader.h"
#include "CppTopicGeneratorGrantlee.h"
#include "DatabaseGeneratorGrantlee.h"
#include "StructBuilder.h"
#include "XmlReader.h"
#include "ui_main_grantlee_gui.h"
#include <nglapplication/nglapplication.h>
#include <NGLLogger/INGLLogger.h>
#include <QFileDialog>
#include <QMessageBox>
#include <grantlee/engine.h>
#include <nglapplication/nglapplication.h>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, m_xmlReader(nullptr)
, m_structBuilder(nullptr)
, m_generator(new CodeGen::CppTopicGeneratorGrantlee)
, m_engine(new Grantlee::Engine)
, m_ui(new Ui_MainGrantleeGui)
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent), m_xmlReader(nullptr), m_structBuilder(nullptr),
m_generator(new CodeGen::CppTopicGeneratorGrantlee), m_engine(new Grantlee::Engine), m_ui(new Ui_MainGrantleeGui)
{
m_idlServiceInfoFile = QStringLiteral("/home/chehrlic/TDS/TDS-build-product-clang/service_idl_files.txt");
m_ui->setupUi(this);
connect(m_ui->actionExit, &QAction::triggered,
this, &MainWindow::close);
connect(m_ui->actionSelect_Data_Source, &QAction::triggered,
this, &MainWindow::onSelectDataSource);
connect(m_ui->actionOpen_Template, &QAction::triggered,
this, &MainWindow::onOpenTemplate);
connect(m_ui->actionSave_Template, &QAction::triggered,
this, &MainWindow::onSaveTemplate);
connect(m_ui->pbRefresh, &QPushButton::clicked,
this, &MainWindow::onRefreshOutput);
connect(m_ui->actionDatabaseGenerator, &QAction::triggered,
this, &MainWindow::onGeneratorDb);
connect(m_ui->actionDDS_Generator, &QAction::triggered,
this, &MainWindow::onGeneratorDds);
m_idlServiceInfoFile = QStringLiteral("/home/chehrlic/TDS/TDS-build-product-clang/service_idl_files.txt");
m_ui->setupUi(this);
connect(m_ui->actionExit, &QAction::triggered, this, &MainWindow::close);
connect(m_ui->actionSelect_Data_Source, &QAction::triggered, this, &MainWindow::onSelectDataSource);
connect(m_ui->actionOpen_Template, &QAction::triggered, this, &MainWindow::onOpenTemplate);
connect(m_ui->actionSave_Template, &QAction::triggered, this, &MainWindow::onSaveTemplate);
connect(m_ui->pbRefresh, &QPushButton::clicked, this, &MainWindow::onRefreshOutput);
connect(m_ui->actionDatabaseGenerator, &QAction::triggered, this, &MainWindow::onGeneratorDb);
connect(m_ui->actionDDS_Generator, &QAction::triggered, this, &MainWindow::onGeneratorDds);
}
MainWindow::~MainWindow()
{
delete m_xmlReader;
delete m_structBuilder;
delete m_generator;
delete m_engine;
delete m_ui;
delete m_xmlReader;
delete m_structBuilder;
delete m_generator;
delete m_engine;
delete m_ui;
}
static QLatin1String s_startDir("/home/chehrlic/TDS/TDS-source-product/Lts/");
void MainWindow::onSelectDataSource()
{
const QString dataSource = QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Service Files (*.xml)"));
if (dataSource.isEmpty())
return;
delete m_xmlReader;
m_xmlReader = new CodeGen::XmlReader;
if (!m_xmlReader->readServiceFile(dataSource, m_idlServiceInfoFile))
{
QMessageBox::warning(this, tr("Invalid data source"), tr("The selected data source is not valid: %1").arg(m_xmlReader->errorString()));
return;
}
delete m_structBuilder;
m_structBuilder = new CodeGen::StructBuilder(m_xmlReader);
if (!m_structBuilder->buildStructures())
{
QMessageBox::warning(this, tr("Invalid data source"), tr("Error building structures from data"));
return;
}
m_ui->teOuput->clear();
m_generator->init(m_xmlReader, m_structBuilder);
QMessageBox::information(this, tr("Data source"), tr("Successfully loaded data source"));
const QString dataSource =
QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Service Files (*.xml)"));
if (dataSource.isEmpty())
return;
delete m_xmlReader;
m_xmlReader = new CodeGen::XmlReader;
if (!m_xmlReader->readServiceFile(dataSource, m_idlServiceInfoFile))
{
QMessageBox::warning(this, tr("Invalid data source"),
tr("The selected data source is not valid: %1").arg(m_xmlReader->errorString()));
return;
}
delete m_structBuilder;
m_structBuilder = new CodeGen::StructBuilder(m_xmlReader);
if (!m_structBuilder->buildStructures())
{
QMessageBox::warning(this, tr("Invalid data source"), tr("Error building structures from data"));
return;
}
m_ui->teOuput->clear();
m_generator->init(m_xmlReader, m_structBuilder);
QMessageBox::information(this, tr("Data source"), tr("Successfully loaded data source"));
}
void MainWindow::onOpenTemplate()
{
const QString templateFile = QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Templates (*.grantlee)"));
if (templateFile.isEmpty())
return;
QFile f(templateFile);
if (!f.open(QIODevice::ReadOnly))
{
QMessageBox::warning(this, tr("Error reading template file"), tr("Can not read file: %1").arg(f.errorString()));
return;
}
const QString content = QString::fromUtf8(f.readAll());
m_ui->teInput->setText(content);
m_templateFile = templateFile;
const QString templateFile =
QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Templates (*.grantlee)"));
if (templateFile.isEmpty())
return;
QFile f(templateFile);
if (!f.open(QIODevice::ReadOnly))
{
QMessageBox::warning(this, tr("Error reading template file"), tr("Can not read file: %1").arg(f.errorString()));
return;
}
const QString content = QString::fromUtf8(f.readAll());
m_ui->teInput->setText(content);
m_templateFile = templateFile;
}
void MainWindow::onSaveTemplate()
{
QFile f(m_templateFile);
if (!f.open(QIODevice::WriteOnly))
{
QMessageBox::warning(this, tr("Error saving template file"), tr("Can not save file: %1").arg(f.errorString()));
return;
}
f.write(m_ui->teInput->toPlainText().toUtf8());
f.close();
QMessageBox::information(this, tr("Saving template file"), tr("Successfully saved template to %1").arg(m_templateFile));
QFile f(m_templateFile);
if (!f.open(QIODevice::WriteOnly))
{
QMessageBox::warning(this, tr("Error saving template file"), tr("Can not save file: %1").arg(f.errorString()));
return;
}
f.write(m_ui->teInput->toPlainText().toUtf8());
f.close();
QMessageBox::information(this, tr("Saving template file"),
tr("Successfully saved template to %1").arg(m_templateFile));
}
void MainWindow::onRefreshOutput()
{
const QString in = m_ui->teInput->toPlainText();
if (!m_generator->setTemplate(QString(), in))
{
m_ui->teOuput->setText(m_generator->errorString());
return;
}
m_ui->teOuput->setText(m_generator->render());
const QString in = m_ui->teInput->toPlainText();
if (!m_generator->setTemplate(QString(), in))
{
m_ui->teOuput->setText(m_generator->errorString());
return;
}
m_ui->teOuput->setText(m_generator->render());
}
void MainWindow::onGeneratorDb()
{
if (dynamic_cast<CodeGen::DatabaseGeneratorGrantlee *>(m_generator))
return;
delete m_generator;
m_generator = new CodeGen::DatabaseGeneratorGrantlee(false);
if (m_xmlReader && m_structBuilder)
m_generator->init(m_xmlReader, m_structBuilder);
if (dynamic_cast<CodeGen::DatabaseGeneratorGrantlee*>(m_generator))
return;
delete m_generator;
m_generator = new CodeGen::DatabaseGeneratorGrantlee(false);
if (m_xmlReader && m_structBuilder)
m_generator->init(m_xmlReader, m_structBuilder);
}
void MainWindow::onGeneratorDds()
{
if (dynamic_cast<CodeGen::CppTopicGeneratorGrantlee *>(m_generator))
return;
delete m_generator;
m_generator = new CodeGen::CppTopicGeneratorGrantlee;
if (m_xmlReader && m_structBuilder)
m_generator->init(m_xmlReader, m_structBuilder);
if (dynamic_cast<CodeGen::CppTopicGeneratorGrantlee*>(m_generator))
return;
delete m_generator;
m_generator = new CodeGen::CppTopicGeneratorGrantlee;
if (m_xmlReader && m_structBuilder)
m_generator->init(m_xmlReader, m_structBuilder);
}
int main(int argc, char **argv)
int main(int argc, char** argv)
{
NGLApplication app(argc, argv);
app.createLogger("CodeGen", "codegen_log4cxx.props");
NGLApplication app(argc, argv);
app.createLogger("CodeGen", "codegen_log4cxx.props");
NGL::INGLLogger &m_logger = app.baseLogger();
STARTUP_LOG(m_logger);
NGL::INGLLogger& m_logger = app.baseLogger();
STARTUP_LOG(m_logger);
int iRet = 0;
{
QScopedPointer<MainWindow> mw(new MainWindow);
mw->show();
iRet = app.exec();
}
int iRet = 0;
{
QScopedPointer<MainWindow> mw(new MainWindow);
mw->show();
iRet = app.exec();
}
SHUTDOWN_LOG(m_logger);
return iRet;
SHUTDOWN_LOG(m_logger);
return iRet;
}
+24 -22
View File
@@ -1,40 +1,42 @@
#pragma once
#include <QObject>
#include <QMainWindow>
#include <QObject>
namespace CodeGen
{
class XmlReader;
class StructBuilder;
class GeneratorGrantleeBase;
}
} // namespace CodeGen
namespace Grantlee
{
class Engine;
}
class Ui_MainGrantleeGui;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private Q_SLOTS:
void onSelectDataSource();
void onOpenTemplate();
void onSaveTemplate();
void onRefreshOutput();
void onGeneratorDb();
void onGeneratorDds();
private:
CodeGen::XmlReader *m_xmlReader;
CodeGen::StructBuilder *m_structBuilder;
CodeGen::GeneratorGrantleeBase *m_generator;
Grantlee::Engine *m_engine;
QString m_idlServiceInfoFile;
QString m_templateFile;
Ui_MainGrantleeGui *m_ui;
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = nullptr);
~MainWindow();
private Q_SLOTS:
void onSelectDataSource();
void onOpenTemplate();
void onSaveTemplate();
void onRefreshOutput();
void onGeneratorDb();
void onGeneratorDds();
private:
CodeGen::XmlReader* m_xmlReader;
CodeGen::StructBuilder* m_structBuilder;
CodeGen::GeneratorGrantleeBase* m_generator;
Grantlee::Engine* m_engine;
QString m_idlServiceInfoFile;
QString m_templateFile;
Ui_MainGrantleeGui* m_ui;
};
@@ -1,16 +1,16 @@
#include <QCoreApplication>
#include <QDir>
#include <QDebug>
#include <QDir>
#include <grantlee/engine.h>
#include <grantlee/templateloader.h>
int main(int argc, char **argv)
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
QString templatesDir = QDir::currentPath();
if (argc > 1) {
if (argc > 1)
{
templatesDir = QString::fromLocal8Bit(argv[1]);
}
@@ -21,7 +21,8 @@ int main(int argc, char **argv)
QDir d(templatesDir);
QStringList files = d.entryList(QStringList() << QStringLiteral("*.grantlee"), QDir::Files);
if (files.isEmpty()) {
if (files.isEmpty())
{
qDebug() << "No .grantlee templates found in" << templatesDir;
// Treat absence as successful parse (nothing to check) to avoid failing
// when directory is empty in different setups.
@@ -29,21 +30,27 @@ int main(int argc, char **argv)
}
bool ok = true;
for (const QString &f : files) {
for (const QString& f : files)
{
Grantlee::Template t;
try {
try
{
t = engine.loadByName(f);
} catch (...) {
}
catch (...)
{
qDebug() << "Exception while loading" << f;
ok = false;
continue;
}
if (!t) {
if (!t)
{
qDebug() << "Failed to load template" << f;
ok = false;
continue;
}
if (t->error() != Grantlee::NoError) {
if (t->error() != Grantlee::NoError)
{
qDebug() << "Parse error in" << f << ":" << t->errorString();
ok = false;
continue;
@@ -51,7 +58,8 @@ int main(int argc, char **argv)
// Render with empty context to ensure rendering path also works.
Grantlee::Context ctx;
QString out = t->render(&ctx);
if (out.isNull()) {
if (out.isNull())
{
qDebug() << "Rendering produced null for" << f;
ok = false;
continue;