
#include <exception>
#include <stdexcept>
#include <QDebug>
#include "db_oper.h"

const int ERROR_MESSAGE_LENGTH = 1001;

using namespace std;

void get_error_message(OCI_Error * pError, char * pszMessage, size_t length);

void initOciLib()
{
	int    returnCode = 0;
	char * pszErrorMessage = (char *)malloc(sizeof(char) * ERROR_MESSAGE_LENGTH);

	returnCode = OCI_Initialize(NULL, NULL, OCI_ENV_DEFAULT);

	if (!returnCode )
	{
		get_error_message(OCI_GetLastError(), pszErrorMessage, ERROR_MESSAGE_LENGTH - 1);

		string message("OCILIB初始化失败！\n");

		message += pszErrorMessage;

		throw runtime_error(message);
	}

	free(pszErrorMessage);
}

void releaseOciLib()
{
	OCI_Cleanup();
}

void get_error_message(OCI_Error * pError, char * pszMessage, size_t length)
{
	//防御性验证
	if (pError == NULL)
	{
		pszMessage[0] = NULL;

		return;
	}

	const otext * psz = OCI_ErrorGetString(pError);

	strcpy_s(pszMessage, length, psz);
}

void error_handler(OCI_Error * pError)
{
	std::runtime_error error(OCI_ErrorGetString(pError));

	OCI_Cleanup();

	throw error;
}

void l_error_handler(OCI_Error* pError)
{
	string errorString = OCI_ErrorGetString(pError);

	std::runtime_error error(OCI_ErrorGetString(pError));

	throw error;
}

void output_error_message( const std::string & errorMessage )
{
	qDebug() << QString::fromLocal8Bit(errorMessage.c_str());
}

std::string get_last_error_message()
{
	OCI_Error * pError = OCI_GetLastError();

	return std::string(OCI_ErrorGetString(pError));
}
