/*
*	©Copyright 2002,2003, Microsoft Corporation
*	Microsoft Confidential.
*	Written by Sergey Vasilevskiy, 2002-2003.
*/

/*
*	Market Watch database class that uses stored procedures for individual frames.
*/

#include "stdafx.h"

using namespace TPCE;

CMarketWatchDB::CMarketWatchDB(CDBConnection *pDBConn)
: CTxnHarnessDBBase(pDBConn)
{
	int i;	

	//Allocate one handle per stored procedure (frame)
	if (SQLAllocHandle(SQL_HANDLE_STMT, m_hdbc, &m_hstmtFrame1) != SQL_SUCCESS)
		ThrowError(CODBCERR::eAllocHandle, SQL_HANDLE_STMT, m_hdbc);	

	//Bind input/output parameters for each stored procedure

	//Frame1 input
	i = 0;
	if (   SQLBindParameter(m_hstmtFrame1, ++i, SQL_PARAM_INPUT, SQL_C_IDENT, SQL_IDENT, 0, 0, &Frame1Input.acct_id, 0, NULL)!=SQL_SUCCESS
		|| SQLBindParameter(m_hstmtFrame1, ++i, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, cIN_NAME_len+1, 0, &Frame1Input.industry_name, cIN_NAME_len+1, NULL)!=SQL_SUCCESS
		|| SQLBindParameter(m_hstmtFrame1, ++i, SQL_PARAM_INPUT, SQL_C_IDENT, SQL_IDENT, 0, 0, &Frame1Input.starting_co_id, 0, NULL)!=SQL_SUCCESS
		|| SQLBindParameter(m_hstmtFrame1, ++i, SQL_PARAM_INPUT, SQL_C_IDENT, SQL_IDENT, 0, 0, &Frame1Input.ending_co_id, 0, NULL)!=SQL_SUCCESS
		|| SQLBindParameter(m_hstmtFrame1, ++i, SQL_PARAM_INPUT, SQL_C_IDENT, SQL_IDENT, 0, 0, &Frame1Input.c_id, 0, NULL)!=SQL_SUCCESS
		|| SQLBindParameter(m_hstmtFrame1, ++i, SQL_PARAM_INPUT, SQL_C_TIMESTAMP, SQL_TIMESTAMP, 23, 3, &Frame1Input.start_day, 0, NULL)!=SQL_SUCCESS
		 )
		ThrowError(CODBCERR::eBindParam, SQL_HANDLE_STMT, m_hstmtFrame1);
	//Frame1 output	
	i = 0;
	if (   SQLBindCol(m_hstmtFrame1, ++i, SQL_C_DOUBLE, &Frame1Output.pct_change, 0, &m_Ind) != SQL_SUCCESS		
		)
		ThrowError(CODBCERR::eBindCol, SQL_HANDLE_STMT, m_hstmtFrame1);
};

void CMarketWatchDB::DoMarketWatchFrame1(const TMarketWatchFrame1Input *pFrame1Input, PMarketWatchFrame1Output pFrame1Output)
{
	int rc;

	//copy input parameters into bound locations
	Frame1Input = *pFrame1Input;

	rc = SQLExecDirect(m_hstmtFrame1, (SQLCHAR*)"{call MarketWatchFrame1(?, ?, ?, ?, ?, ?)}", SQL_NTS);
	if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
		ThrowError(CODBCERR::eExecDirect, SQL_HANDLE_STMT, m_hstmtFrame1, "DoMarketWatchFrame1");

	if ( SQLFetch(m_hstmtFrame1) == SQL_ERROR)
		ThrowError(CODBCERR::eFetch, SQL_HANDLE_STMT, m_hstmtFrame1, "DoMarketWatchFrame1");

	//copy output parameters back
	if (m_Ind != SQL_NULL_DATA)
	{		
		*pFrame1Output = Frame1Output;	//invoke default assignment operator
	}
	else
	{	// no stocks were found => change is 0
		Frame1Output.pct_change = 0;

		*pFrame1Output = Frame1Output;	//invoke default assignment operator
	}

	if ( (rc = SQLCloseCursor(m_hstmtFrame1)) != SQL_SUCCESS)
		ThrowError(CODBCERR::eCloseCursor, SQL_HANDLE_STMT, m_hstmtFrame1, "DoMarketWatchFrame1");
};

void CMarketWatchDB::Cleanup(void* pException)
{
	SQLCloseCursor(m_hstmtFrame1);
}
