#include "TableHelper.h"

#include <QStringList>

TableHelper::TableHelper()
{

}

QString TableHelper::createTable(const QString &tablename, const QList<QPair<QString, QString> > &fieldAndTypes)
{
    QStringList fields;
    foreach(auto &item, fieldAndTypes)
    {
        if(item.second == "DATETIME")
            fields << item.first +" DATE" ;
        else
            fields << item.first +" " +  item.second;
    }
    return QString("create table %1 ( \n %2 \n ); \n").arg(tablename).arg(fields.join(", \n"));
}

QString TableHelper::createComment(const QString &tablename, const QList<QPair<QString, QString> > &fieldAndComments)
{
    QStringList comments;
    foreach(auto &item, fieldAndComments)
    {
        comments << QString("COMMENT ON COLUMN %1.%2 IS '%3'; ").arg(tablename).arg(item.first).arg(item.second);
    }
    return comments.join("\n");
}

QString TableHelper::createPrimaryAlter(const QString &tablename)
{
    return QString("alter table %1 add constraint PK_%1_Id primary key(ID);").arg(tablename);
}

QString TableHelper::createSeq(const QString &tablename)
{
    return QString("CREATE SEQUENCE SEQ_%1 \n\
                    START WITH 1 \n\
                    MAXVALUE 99999999999999 \n\
                    MINVALUE 1 \n\
                    CYCLE \n\
                    CACHE 20 \n\
                    ORDER;").arg(tablename);
}

QString TableHelper::createTrigger(const QString &tablename)
{
    return QString("create or replace trigger %1_TRIGGER \n\
                    before insert on %1  \n\
                    for each row     \n\
                    begin   \n\
                    select  SEQ_%1.nextval into :new.ID from dual;\n\
            end;").arg(tablename);
}

QString TableHelper::createDescription(const QString &entityname,const QList<QPair<QString, QString> > &fieldAndComments)
{
    QStringList descriptions;
    foreach(auto &item, fieldAndComments)
    {
        descriptions << QString("pData = t.data(& %1::m_%2, \"%2\", 0, true, true);\n \
                pData->setDescription(\"%3\");\n").arg(entityname).arg(item.first).arg(item.second);
    }
    return descriptions.join("\n");
}
