#include "DatabaseConnector.h"
#include "MessageException.h"
#include "QxOrm.h"
#include "SqlGenerator_Oracle.h"

#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlDriver>
#include <QDebug>
#include <QMessageBox>

DatabaseConnector::DatabaseConnector()
	:status(false)
{
}

DatabaseConnector::~DatabaseConnector()
{
}

/**
 * @brief DatabaseConnector::init 连接数据库
 * @param databaseName 数据库名
 * @param hostName 主机
 * @param userName 用户名
 * @param password 密码
 */
void DatabaseConnector::init(const QString &databaseName,
                             const QString &hostName,
							 const quint16 port,
                             const QString &userName,
                             const QString &password)
{
    qx::QxSqlDatabase *qxSqlDatabase = qx::QxSqlDatabase::getSingleton();
    qxSqlDatabase->setDriverName("QOCI");
    qxSqlDatabase->setDatabaseName(databaseName);
    qxSqlDatabase->setHostName(hostName);
    qxSqlDatabase->setUserName(userName);
    qxSqlDatabase->setPassword(password);
    qxSqlDatabase->setPort(port);
    std::shared_ptr<SqlGenerator_Oracle> sqlGenerator_ptr= std::make_shared<SqlGenerator_Oracle>();
    qxSqlDatabase->setSqlGenerator(sqlGenerator_ptr);
}

/**
 * @brief DatabaseConnector::isOpen 数据库是否已连接
 * @return 是否连接
 */
bool DatabaseConnector::isOpen()
{
	status = qx::QxSqlDatabase::getSingleton()->getDatabase().isOpen();
    return  status;
}

void DatabaseConnector::transaction()
{
	bool ret = qx::QxSqlDatabase::getSingleton()->getDatabase().transaction();
	if (!ret)
	{
		QString msg = qx::QxSqlDatabase::getSingleton()->getDatabase().lastError().text();
		qDebug() << "transaction:" << msg;
		throw MessageException("开启事务失败！");
	}
}

void DatabaseConnector::commit()
{
	bool ret = qx::QxSqlDatabase::getSingleton()->getDatabase().commit();
	if (!ret)
	{
		qDebug() << "commit:" << qx::QxSqlDatabase::getSingleton()->getDatabase().lastError().text();
		throw MessageException("提交事务失败！");
	}
}

void DatabaseConnector::rollback()
{
	bool ret = qx::QxSqlDatabase::getSingleton()->getDatabase().rollback();
	if (!ret)
	{
		qDebug() << "rollback:" << qx::QxSqlDatabase::getSingleton()->getDatabase().lastError().text();
		throw MessageException("回滚事务失败！");
	}
}
