/*************************************************************************
*
*	open.c		    6/10/93
*
*	This file is about SQLOpen for WinWord ODBC
*
*************************************************************************/

#include "wbodbc.h"

/******************************************************************
*
*	wdAllocHandle -- to allocate a ODBCHNDL
*
*******************************************************************/
SWORD wdAllocHandle(ODBCHNDL **hODBC, HDBC hdbc)
{
	ODBCHNDL	*htemp;
	
	if (*hODBC == NULL) 
		{
		*hODBC = (ODBCHNDL *) malloc(sizeof(ODBCHNDL));
		if (*hODBC == NULL) 
			{
			wdMessageBox(OUTOFMEMORY);
			return(0);
			}
		(*hODBC)->next = NULL;
		(*hODBC)->hdbc = hdbc;
		(*hODBC)->hstmt = 0;
		(*hODBC)->synchronize_flag = 0;
		(*hODBC)->lpDBList = NULL;
		(*hODBC)->connect_id = 1;
		(*hODBC)->lpSchemaTable = NULL;
		return((*hODBC)->connect_id);
		} 
	else 
		{
		htemp = *hODBC;
		while(htemp->next) 
			htemp = htemp->next;
		htemp->next = (ODBCHNDL *) malloc(sizeof(ODBCHNDL));
		if (htemp->next == NULL) 
			{
			wdMessageBox(OUTOFMEMORY);
			return(0);
			}
		htemp->next->next = NULL;
		htemp->next->hdbc = hdbc;
		htemp->next->hstmt = 0;
		htemp->next->lpDBList = NULL;
		htemp->next->synchronize_flag = 0;
		htemp->next->connect_id = htemp->connect_id+1;
		htemp->next->lpSchemaTable = NULL;
		return(htemp->next->connect_id);
		}
}

UWORD driver_completion[4] = 
{
	SQL_DRIVER_PROMPT,
	SQL_DRIVER_COMPLETE,
	SQL_DRIVER_COMPLETE_REQUIRED,
	SQL_DRIVER_NOPROMPT
};

/******************************************************************
*
*	sql_open -- the entrance of SQLOpen function
*
*******************************************************************/
SWORD WINAPI _loadds SQLOpen(LPSTR connection_string, LPSTR output_string, SWORD driver_prompt)
{
	HDBC		hdbc;
	SWORD		length;
	RETCODE		retcode;
	DLLLIST		*dlllist_temp;
	
	dlllist_temp = wdGetVBlock(TRUE);
	if (dlllist_temp == NULL)
		{
		if(henv)
			return(SQL_OutOfMemory);
		else
			return(0);
		}
	
	if(driver_prompt<1 || driver_prompt>4)
		driver_prompt = 2;
	
	if (SQLAllocConnect(henv, &hdbc) != SQL_SUCCESS) 
		{
		wdSQLError(henv, NULL, NULL);
		return(0);
		}
	
	if (hdbc == NULL) 
		return(0);
	
	retcode = SQLSetConnectOption(hdbc, SQL_LOGIN_TIMEOUT, 30);
	if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) 
		{
		wdSQLError(henv, hdbc, NULL);
		SQLFreeConnect(hdbc);
		return(0);
		}
	
	retcode = SQLDriverConnect(hdbc, GetActiveWindow(), connection_string, SQL_NTS, 
					(LPSTR)szResource, 256, &length, driver_completion[driver_prompt - 1]);
	if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) 
		{
		wdSQLError(henv, hdbc, NULL);
		SQLFreeConnect(hdbc);
		return(0);
		}
	
	if(output_string)
		_fstrcpy(output_string,szResource);
	
	if (!(retcode=wdAllocHandle(&(dlllist_temp->hODBC), hdbc))) 
		{
		SQLDisconnect(hdbc);
		SQLFreeConnect(hdbc);
		return(SQL_OutOfMemory);
		}
	
	return(retcode);
}
