Esempio n. 1
0
void remove_catalogs(void)
{	
	SQLRETURN	retcode;
	void        remove_update_queue_tables(void);

    sql_db_connection = (TM_CONNECTION *)malloc(sizeof(TM_CONNECTION));

	// Allocate an environment handle
	retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &(sql_db_connection->henv));

	if( retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO )
	{
		/* Set the ODBC version environment attribute */
		retcode = SQLSetEnvAttr(sql_db_connection->henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);

		if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
		{
			/* Allocate a connection handle */
			retcode = SQLAllocHandle(SQL_HANDLE_DBC, sql_db_connection->henv, &(sql_db_connection->hdbc));

			if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
			{
				/* Connect to data source */
				retcode = SQLConnect(sql_db_connection->hdbc, (SQLCHAR*) odbc_dsn, SQL_NTS,
					(SQLCHAR*) username, SQL_NTS,
					(SQLCHAR*) password, SQL_NTS);

				if( retcode  == SQL_ERROR )
				{
					SQLFreeHandle(SQL_HANDLE_DBC, sql_db_connection->hdbc);
					SQLFreeHandle(SQL_HANDLE_ENV, sql_db_connection->henv);
        			printf ("Error: unable to connect to SQL Server\n");
       				puts ("Ensure that the DBMS is running and that your ODBC DSN settings are correct.");
        			exit (EXIT_FAILURE);
				}
			}
			else
			{
				SQLFreeHandle(SQL_HANDLE_DBC, sql_db_connection->hdbc);
				SQLFreeHandle(SQL_HANDLE_ENV, sql_db_connection->henv);
        		printf ("Error: unable to connect to SQL Server\n");
       			puts ("Ensure that the DBMS is running and that your ODBC DSN settings are correct.");
        		exit (EXIT_FAILURE);
			}
		}
	}
	else
	{
		SQLFreeHandle(SQL_HANDLE_ENV, sql_db_connection->henv);
        printf ("Error: unable to connect to SQL Server\n");
       	puts ("Ensure that the DBMS is running and that your ODBC DSN settings are correct.");
        exit (EXIT_FAILURE);
	}

	printf ("\n\nConnected to SQL Server.\n\n");

	puts ("Removing Vigilert's catalogs will delete your Vigilert triggers,");
	puts ("triggersets, data sources, pending mail, pending OS commands, and pending notices.");
	printf ("Are you sure you want to do this (Y/N)? ");
	fgets (yesno, sizeof (yesno), stdin);
    yesno[strlen (yesno) - 1] = '\0';  // Remove trailing \n.

	if (stricmp (yesno, "y") != 0)
	{
		exit (EXIT_SUCCESS);
	}

	puts ("");

	remove_update_queue_tables();

	exec_sql_stmt("drop table vl_DataSrc");
	puts ("vl_DataSrc");

	exec_sql_stmt("drop table vl_DataSrcAtb"),
	puts ("vl_datasrcatb");

	exec_sql_stmt("drop table vl_IDTable");
	puts ("vl_idtable");

	exec_sql_stmt("drop table vl_TriggerSet");
	puts ("vl_TriggerSet");

	exec_sql_stmt("drop table vl_Trigger");
	puts ("vl_Trigger");

	exec_sql_stmt("drop table vl_TrigDataSrcReln");
	puts ("vl_TrigDataSrcReln");

	exec_sql_stmt("drop table vl_mail");
	puts ("vl_mail");

	exec_sql_stmt("drop table vl_osexec");
	puts ("vl_osexec");

	exec_sql_stmt("drop table vl_notice");
	puts ("vl_notice");

	exec_sql_stmt("drop table vl_DataSrcMtb");
	puts ("vl_DataSrcMtb");

	exec_sql_stmt("drop table vl_null_tbl");
	puts ("vl_null_tbl");

	exec_sql_stmt("drop table vl_mon_watch");
	puts ("vl_mon_watch");

	exec_sql_stmt("drop table vl_mon_update");
	puts ("vl_mon_update");

	exec_sql_stmt("drop table vl_ext_fcn_tbl");
	puts ("vl_ext_fcn_tbl");
}
Esempio n. 2
0
 ConnectionHolder(Environment &env)
 {
   if (SQLAllocHandle(SQL_HANDLE_DBC, env.GetHolder().GetHandle(), &Conn) != SQL_SUCCESS)
     throw ConnectionException("Error allocate connection", ceErrorAllocConnection);
 }
Esempio n. 3
0
CDBBinary CODBCRecordset::SelectBinary(const CString& strQuery)
{
	CDBBinary DBBinary(5, 5);

	DBBinary.Clear();

	DBBinary.SetCurUsedSize(-1);

	if (0 == strQuery.GetLength())
	{
		return DBBinary;
	}

	HSTMT			hStmt;
	unsigned char	Data[BINARY_FIELD_MAX_SIZE] = {0};
	SQLLEN		ind = SQL_DATA_AT_EXEC;

	if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, m_pDatabase->GetConn(), &hStmt))
	{
		return DBBinary;
	}

	SQLPrepare(hStmt, SQLData(strQuery), SQL_NTS);

	if (SQL_ERROR == SQLBindParameter(hStmt, 1, SQL_PARAM_OUTPUT, SQL_C_BINARY, SQL_BINARY, BINARY_FIELD_MAX_SIZE,
		0, (SQLPOINTER)Data, BINARY_FIELD_MAX_SIZE, &ind))
	{
		return DBBinary;
	}

	if (SQL_ERROR == SQLExecute(hStmt))
	{
		return DBBinary;
	}

	SQLLEN sqlLen;

	DBBinary.Begin();

	while (SQL_SUCCESS == SQLFetch(hStmt))
	{
		if (!m_pDatabase->IsOpen())
		{
			DBBinary.SetCurUsedSize(-1);
			return DBBinary;
		}

		if (SQL_ERROR == SQLGetData(hStmt, 1, SQL_BINARY, (SQLPOINTER)Data, BINARY_FIELD_MAX_SIZE, &sqlLen))
		{
			DBBinary.SetCurUsedSize(-1);
			return DBBinary;
		}

		if (-1 == sqlLen)
		{
			if (0 != DBBinary.InsertData(Data, 0))
			{
				DBBinary.SetCurUsedSize(-1);
				return DBBinary;
			}
			continue;
		}

		if (SQL_ERROR == SQLGetData(hStmt, 1, SQL_C_DEFAULT, (SQLPOINTER)Data, sqlLen, &ind))
		{
			DBBinary.SetCurUsedSize(-1);
			return DBBinary;
		}

		if (sqlLen != DBBinary.InsertData(Data, sqlLen))
		{
			DBBinary.SetCurUsedSize(-1);
			return DBBinary;
		}
	}

	SQLFreeHandle(SQL_HANDLE_STMT, hStmt);

	return DBBinary;
}
Esempio n. 4
0
static int odbc_dispatch11(void)
{
	unsigned long retval;
	PWord rval; int rtype;
	PWord arg1; int type1;
	PWord arg2; int type2;
	PWord arg3; int type3;
	PWord arg4; int type4;
	PWord arg5; int type5;

	PI_getan(&arg1,&type1,1);
	if (type1 != PI_INT)
		if (!CI_get_integer((unsigned long *)&arg1,type1))
			PI_FAIL;
	PI_getan(&arg2,&type2,2);
	if (type2 != PI_INT)
		if (!CI_get_integer((unsigned long *)&arg2,type2))
			PI_FAIL;
	PI_getan(&arg3,&type3,3);
	if (type3 != PI_INT)
		if (!CI_get_integer((unsigned long *)&arg3,type3))
			PI_FAIL;
	PI_getan(&arg4,&type4,4);
	if (type4 != PI_INT)
		if (!CI_get_integer((unsigned long *)&arg4,type4))
			PI_FAIL;
	PI_getan(&arg5,&type5,5);


	switch(arg1)
	{
		case 0:
			retval = (unsigned long) SQLAllocHandleStd(((SQLSMALLINT  ) arg2),((SQLHANDLE  ) arg3),((SQLHANDLE * ) arg4));
			break;
		case 1:
			retval = (unsigned long) SQLParamOptions(((SQLHSTMT  ) arg2),((SQLUINTEGER  ) arg3),((SQLUINTEGER * ) arg4));
			break;
		case 2:
			retval = (unsigned long) SQLTransact(((SQLHENV  ) arg2),((SQLHDBC  ) arg3),((SQLUSMALLINT  ) arg4));
			break;
		case 3:
			retval = (unsigned long) SQLSetStmtOption(((SQLHSTMT  ) arg2),((SQLUSMALLINT  ) arg3),((SQLUINTEGER  ) arg4));
			break;
		case 4:
			retval = (unsigned long) SQLSetConnectOption(((SQLHDBC  ) arg2),((SQLUSMALLINT  ) arg3),((SQLUINTEGER  ) arg4));
			break;
		case 5:
			retval = (unsigned long) SQLPutData(((SQLHSTMT  ) arg2),((SQLPOINTER  ) arg3),((SQLINTEGER  ) arg4));
			break;
		case 6:
			retval = (unsigned long) SQLGetStmtOption(((SQLHSTMT  ) arg2),((SQLUSMALLINT  ) arg3),((SQLPOINTER  ) arg4));
			break;
		case 7:
			retval = (unsigned long) SQLGetFunctions(((SQLHDBC  ) arg2),((SQLUSMALLINT  ) arg3),((SQLUSMALLINT * ) arg4));
			break;
		case 8:
			retval = (unsigned long) SQLGetConnectOption(((SQLHDBC  ) arg2),((SQLUSMALLINT  ) arg3),((SQLPOINTER  ) arg4));
			break;
		case 9:
			retval = (unsigned long) SQLFetchScroll(((SQLHSTMT  ) arg2),((SQLSMALLINT  ) arg3),((SQLINTEGER  ) arg4));
			break;
		case 10:
			retval = (unsigned long) SQLEndTran(((SQLSMALLINT  ) arg2),((SQLHANDLE  ) arg3),((SQLSMALLINT  ) arg4));
			break;
		case 11:
			retval = (unsigned long) SQLAllocHandle(((SQLSMALLINT  ) arg2),((SQLHANDLE  ) arg3),((SQLHANDLE * ) arg4));
			break;
		default:
			PI_FAIL;
	}
	PI_makedouble(&rval,&rtype,(double) retval);
	if (PI_unify(arg5,type5,rval,rtype))
		PI_SUCCEED;
	PI_FAIL;
}
Esempio n. 5
0
static isc_result_t
odbc_connect(odbc_instance_t *dbi, odbc_db_t **dbc) {

    odbc_db_t *ndb = *dbc;
    SQLRETURN sqlRes;
    isc_result_t result = ISC_R_SUCCESS;

    if (ndb != NULL) {
        /*
         * if db != null, we have to do some cleanup
         * if statement handle != null free it
         */
        if (ndb->stmnt != NULL) {
            SQLFreeHandle(SQL_HANDLE_STMT, ndb->stmnt);
            ndb->stmnt = NULL;
        }

        /* if connection handle != null free it */
        if (ndb->dbc != NULL) {
            SQLFreeHandle(SQL_HANDLE_DBC, ndb->dbc);
            ndb->dbc = NULL;
        }
    } else {
        ndb = isc_mem_allocate(ns_g_mctx, sizeof(odbc_db_t));
        if (ndb == NULL) {
            isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                          DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
                          "Odbc driver unable to allocate memory");
            return ISC_R_NOMEMORY;
        }
        memset(ndb, 0, sizeof(odbc_db_t));
    }

    sqlRes = SQLAllocHandle(SQL_HANDLE_DBC, dbi->sql_env, &(ndb->dbc));
    if (!sqlOK(sqlRes)) {
        isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
                      "Odbc driver unable to allocate memory");
        result = ISC_R_NOMEMORY;
        goto cleanup;
    }

    sqlRes = SQLConnect(ndb->dbc, dbi->dsn, safeLen(dbi->dsn), dbi->user,
                        safeLen(dbi->user), dbi->pass, safeLen(dbi->pass));
    if (!sqlOK(sqlRes)) {
        isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
                      "Odbc driver unable to connect");
        result = ISC_R_FAILURE;
        goto cleanup;
    }

    sqlRes = SQLAllocHandle(SQL_HANDLE_STMT, ndb->dbc, &(ndb->stmnt));
    if (!sqlOK(sqlRes)) {
        isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
                      "Odbc driver unable to allocate memory");
        result = ISC_R_NOMEMORY;
        goto cleanup;
    }

    *dbc = ndb;

    return ISC_R_SUCCESS;

cleanup:

    if (ndb != NULL) {

        /* if statement handle != null free it */
        if (ndb->stmnt != NULL) {
            SQLFreeHandle(SQL_HANDLE_STMT, ndb->stmnt);
            ndb->stmnt = NULL;
        }

        /* if connection handle != null free it */
        if (ndb->dbc != NULL) {
            SQLDisconnect(ndb->dbc);
            SQLFreeHandle(SQL_HANDLE_DBC, ndb->dbc);
            ndb->dbc = NULL;
        }
        /* free memory holding ndb */
        isc_mem_free(ns_g_mctx, ndb);
    }

    return result;
}
Esempio n. 6
0
int main()
{
  SQLHENV env;
  SQLHDBC dbc;
  SQLHSTMT stmt;
  SQLRETURN ret;
  SQLCHAR outstr[1024];
  SQLSMALLINT outstrlen;
  
  // Aloocate an environment handle
  ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env);
  checkrc(ret,__LINE__);
  
   //we need odbc3 support
   SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);
   
  //ALLOCATE A Connection handle
  ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc);
  checkrc(ret,__LINE__);
    
  // connect to the DSN mydsn
   ret = SQLConnect (dbc,
                   (SQLCHAR *) "test", (SQLSMALLINT) strlen ("test"),
                   (SQLCHAR *) "root",
                   (SQLSMALLINT) strlen ("root"),
                   (SQLCHAR *) "manager",
                   (SQLSMALLINT) strlen (""));

  if(SQL_SUCCEEDED(ret))
  {
     printf("\nConnected to the Data Source..\n");
     
     
  }
   else
   {
        printf("error in connection\n");
        
        ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
        checkrc(ret,__LINE__);

        ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
        checkrc(ret,__LINE__); 
        return 1;
    }

   
   //******************************************************************
   // TABLE CREATED
   ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt);
   checkrc(ret,__LINE__);
   
   SQLCHAR table[200]=
     "CREATE TABLE T1(F1 INT,F2 INT)";
   ret = SQLPrepare(stmt,table,SQL_NTS);
   checkrc(ret,__LINE__);
   ret = SQLExecute(stmt);
   printf("\nTABLE CREATED\n"); 
   //****************************************************************
   
   InsertTest(env,dbc,stmt);  
   //*****************************************************************
    int ret1;
    ret1=FetchTest(env,dbc,stmt);

   //****************************************************************      
   ret = SQLPrepare(stmt,(unsigned char*)"drop table T1;",SQL_NTS);
   checkrc(ret,__LINE__);

   ret = SQLExecute(stmt);
   checkrc(ret,__LINE__);
   printf("Table 'T1' Dropped\n");

   ret = SQLFreeHandle(SQL_HANDLE_STMT,stmt);
   checkrc(ret,__LINE__);

   ret = SQLDisconnect(dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
   checkrc(ret,__LINE__);
   
   if(ret1 == 0)return 1;
   return 0;
}         
Esempio n. 7
0
int main(int argc, char * argv[])
{
	HDBC    hdbc;
	HENV    henv;
	HSTMT   hstmt;
	RETCODE rc;
	UCHAR   uid[UID_LEN];
	UCHAR   pwd[PWD_LEN];
	UCHAR   file[OPT1_LEN];
	UCHAR   dsn[DSN_LEN];
	
	uid[0]  = (UCHAR)NULL;
	file[0] = (UCHAR)NULL;
	dsn[0]  = (UCHAR)NULL;
	pwd[0]  = (UCHAR)NULL;
	
	if (argc > 1) 
	{
		int argIndex;   /* Input argument index         */
		int argCount;   /* Running count of arguments   */
		
		for (argCount=argc-1, argIndex=1; argCount > 0;
		argIndex++, argCount--) 
		{
			switch (ArgParse(argv[argIndex])) 
			{
			case HELP_ARG:
				printf(USAGE_MSG1, argv[0]);
				return(1);
			case PWD_ARG:
				argIndex++;
				if (argCount <= 1) 
				{
					printf(PWD_ERR1);
					printf(USAGE_MSG1, argv[0]);
					return(1);
				}
				if (strlen(argv[argIndex]) > PWD_LEN) 
				{
					printf(PWD_MSG1, PWD_LEN);
					return(1);
				}
				strcpy((char*)pwd, argv[argIndex]);
				argCount--;
				break;
			case UID_ARG:
				argIndex++;
				if (argCount <= 1) {
					printf(UID_ERR1);
					printf(USAGE_MSG1, argv[0]);
					return(1);
				}
				if (strlen(argv[argIndex]) > UID_LEN) 
				{
					printf(UID_MSG1, UID_LEN);
					return(1);
				}
				strcpy((char*)uid, argv[argIndex]);
				argCount--;
				break;
			case DSN_ARG:
				argIndex++;
				if (argCount <= 1) 
				{
					printf(DSN_ERR1);
					printf(USAGE_MSG1, argv[0]);
					return(1);
				}
				if (strlen(argv[argIndex]) > DSN_LEN) 
				{
					printf(DSN_MSG1, DSN_LEN);
					return(1);
				}
				strcpy((char*)dsn, argv[argIndex]);
				argCount--;
				break;
			case FILE_ARG:
				argIndex++;
				if (argCount <= 1) 
				{
					printf(FILE_ERR1);
					printf(USAGE_MSG1, argv[0]);
					return(1);
				}
				if (strlen(argv[argIndex]) > OPT1_LEN)
				{
					printf(FILE_MSG1, OPT1_LEN);
					return(1);
				}
				strcpy((char*)file, argv[argIndex]);
				argCount--;
				break;
			}
		}
	}
	else 
	{
		printf(USAGE_MSG1, argv[0]);
		return(1);
	}
#if !defined (__cplusplus) && defined (hppa)
	/*
	** C programs must call the HP C++ Object initializer function.
	*/
	_main ();
#endif
	
	rc = SQLAllocHandle (SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
	if ((rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO))
	{
		printf("Failed to initialize ODBC environmment...\n");
		exit(255);      /* Exit with failure */
	}
	ODBC_initialize ( &henv );
	ODBC_prepareCon ( henv, &hdbc );
	rc = ODBC_connect(henv, hdbc, dsn, uid, pwd);
	if ((rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO))
		exit(255);      /* Exit with failure */
						/*
						** Allocate a HSTMT to communicate with ODBC DB Driver.
	*/
	rc = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
	if ((rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO)) 
	{
		printf ("Unable to Allocate a statement handle.\n");
		ODBC_getErrorInfo (henv, hdbc, hstmt);
		ODBC_releaseEnv(henv, hdbc);
		exit (255);
	}
	
	if(file[0] == (UCHAR) NULL)
	{
		printf("\nPlease enter SQL script file: ");
		scanf("%s", (char*)file);	
	}
	ODBC_fileRead ((char*)file, henv, hdbc, hstmt);
	
	SQLFreeHandle (SQL_HANDLE_STMT, hstmt);
	ODBC_releaseEnv (henv, hdbc);
	
	return(0);
}
bool OdbcConnection::Connect()
{
	if (m_szDSN.length() == 0)
		return false;

	m_lock.Acquire();

	tstring szConn = _T("DSN=") + m_szDSN + _T(";");
	// Reconnect if we need to.
	if (isConnected())
		Disconnect();

	// Allocate enviroment handle
	if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_envHandle)))
	{
		ReportSQLError(SQL_HANDLE_ENV, m_envHandle, _T("SQLAllocHandle"), _T("Unable to allocate environment handle."));
		goto error_handler;
	}

	// Request ODBC3 support
	if (!SQL_SUCCEEDED(SQLSetEnvAttr(m_envHandle, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0)))
	{
		ReportSQLError(SQL_HANDLE_ENV, m_envHandle, _T("SQLSetEnvAttr"), _T("Unable to set environment attribute (SQL_ATTR_ODBC_VERSION)."));
		goto error_handler;
	}

	// Allocate the connection handle
	if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_DBC, m_envHandle, &m_connHandle)))
	{
		ReportSQLError(SQL_HANDLE_ENV, m_envHandle, _T("SQLAllocHandle"), _T("Unable to allocate connection handle."));
		goto error_handler;
	}

	if (m_szUser.length())
	{
		szConn += _T("UID=") + m_szUser + _T(";");
		if (m_szPass.length())
			szConn += _T("PWD=") + m_szPass + _T(";");
	}

	// Enable multiple active result sets
	if (m_bMarsEnabled)
		szConn += _T("MARS_Connection=yes;");

	if (!SQL_SUCCEEDED(SQLDriverConnect(m_connHandle, NULL, (SQLTCHAR *)szConn.c_str(), SQL_NTS, NULL, NULL, NULL, NULL)))
	{
		ReportSQLError(SQL_HANDLE_DBC, m_connHandle, _T("SQLDriverConnect"), _T("Unable to establish connection."));
		goto error_handler;
	}

	for (auto itr = m_commandSet.begin(); itr != m_commandSet.end(); itr++)
		(*itr)->SetConnectionHandle(m_connHandle);

	m_lock.Release();
	return true;

error_handler:
	ResetHandles();
	m_lock.Release();
	return false;
}
Esempio n. 9
0
int main()
{
  SQLHENV env;
  SQLHDBC dbc;
  SQLHSTMT stmt;
  SQLRETURN ret;
  SQLCHAR outstr[1024];
  SQLSMALLINT outstrlen;
  
  // Aloocate an environment handle
  ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env);
  checkrc(ret,__LINE__);
  
   //we need odbc3 support
   ret =SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);
   checkrc(ret,__LINE__);
  //ALLOCATE A Connection handle
  ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc);
  checkrc(ret,__LINE__);
    
  // connect to the DSN mydsn
   ret = SQLConnect (dbc,
                   (SQLCHAR *) "DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;"),
                   (SQLCHAR *) "root",
                   (SQLSMALLINT) strlen ("root"),
                   (SQLCHAR *) "manager",
                   (SQLSMALLINT) strlen (""));

  if(SQL_SUCCEEDED(ret))
  {
     printf("\nConnected to the Data Source..\n");
       
     
  }
   else
   {
        printf("error in connection\n");
        ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
        checkrc(ret,__LINE__);

        ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
        checkrc(ret,__LINE__); 
        return 1;
   }

   ret = SQLSetConnectAttr(dbc,SQL_ATTR_AUTOCOMMIT,(void*)SQL_AUTOCOMMIT_OFF,SQL_IS_UINTEGER);
   checkrc(ret,__LINE__);
   //******************************************************************
   // TABLE CREATED
   ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt);
   checkrc(ret,__LINE__);
   
   SQLCHAR table[200]=
     "CREATE TABLE T1(F1 INT,F2 INT);";
   ret = SQLPrepare(stmt,table,SQL_NTS);
   checkrc(ret,__LINE__);
   ret = SQLExecute(stmt);
   checkrc(ret,__LINE__);
   SQLFreeStmt(stmt, SQL_CLOSE);
   
   printf("\nTABLE CREATED\n"); 
   //****************************************************************
    ret = SQLPrepare(stmt,(unsigned char*)"INSERT INTO T1 VALUES(1,1);",SQL_NTS);
    checkrc(ret,__LINE__);
    ret = SQLExecute(stmt);
    checkrc(ret,__LINE__);
    
    SQLFreeStmt(stmt, SQL_CLOSE);
    ret = SQLEndTran(SQL_HANDLE_DBC,dbc,SQL_COMMIT);
    if(ret!=SQL_SUCCESS && ret !=SQL_SUCCESS_WITH_INFO)
    printf("error in commit\n");
   //InsertTest(env,dbc,stmt);  
   //*****************************************************************
    
    //update
    ret = SQLPrepare(stmt,(unsigned char*)"UPDATE T1 SET F2=100;",SQL_NTS);
    checkrc(ret,__LINE__);
    ret = SQLExecute(stmt);
    checkrc(ret,__LINE__);
    SQLFreeStmt(stmt, SQL_CLOSE);
    ret = SQLEndTran(SQL_HANDLE_DBC,dbc,SQL_COMMIT);
    if(ret!=SQL_SUCCESS && ret !=SQL_SUCCESS_WITH_INFO)
    printf("error in commit\n");
    checkrc(ret,__LINE__);
   //***********************************************************
     //FETCH
    FetchTest(env,dbc,stmt);

   //****************************************************************      
   ret = SQLExecDirect(stmt,(unsigned char*)"DROP TABLE T1",SQL_NTS);
   checkrc(ret,__LINE__);
   SQLFreeStmt(stmt, SQL_CLOSE);
   printf("Table T1 dropped\n");

   ret = SQLFreeHandle(SQL_HANDLE_STMT,stmt);
   checkrc(ret,__LINE__);

   ret = SQLDisconnect(dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
   checkrc(ret,__LINE__);
   return 0;
}         
Esempio n. 10
0
OdbcHandle odbcConnect(const char* dbname,
                       const char* servername,
                       const char* username,
                       const char* driver,
                       const char* password)

{
   OdbcHandle handle = new OdbcControlStruct;

   if (handle)
   {
      if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_ENV,
                                        SQL_NULL_HANDLE,
                                        &handle->mEnvironmentHandle)))
      {
         Os::Logger::instance().log(FAC_ODBC, PRI_ERR,
                       "odbcConnect: Failed to allocate "
                       "environment handle");
         delete handle;
         handle = NULL;
      }
      else
      {
         SQLSetEnvAttr(handle->mEnvironmentHandle, SQL_ATTR_ODBC_VERSION,
                       (void*) SQL_OV_ODBC3, 0);

         if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_DBC,
                                            handle->mEnvironmentHandle,
                                            &handle->mConnectionHandle)))
         {
            Os::Logger::instance().log(FAC_ODBC, PRI_ERR,
                          "odbcConnect: Failed to allocate "
                          "connection handle");
            extract_error("SQLSetEnvAttr", handle->mEnvironmentHandle, SQL_HANDLE_ENV);
            SQLFreeHandle(SQL_HANDLE_ENV, handle->mEnvironmentHandle);
            delete handle;
            handle = NULL;
         }
         else
         {
            // Connect - contruct connection string
            UtlString connectionString;
            char temp[128];

            if (dbname)
            {
               sprintf(temp, "DATABASE=%s;", dbname);
               connectionString.append(temp);
            }
            if (servername)
            {
               sprintf(temp, "SERVER=%s;", servername);
               connectionString.append(temp);
            }
            if (username)
            {
               sprintf(temp, "UID=%s;", username);
               connectionString.append(temp);
            }
            if (password)
            {
               sprintf(temp, "PWD=%s;", password);
               connectionString.append(temp);
            }
            else
            {
               connectionString.append("PWD=;");
            }
            if (driver)
            {
               sprintf(temp, "DRIVER=%s;", driver);
               connectionString.append(temp);
            }
            // Connect in read/write mode
            connectionString.append("READONLY=0;");

            SQLRETURN sqlRet =
                  SQLDriverConnect(handle->mConnectionHandle,
                                   NULL,
                                   (SQLCHAR*)connectionString.data(),
                                   SQL_NTS,
                                   NULL,
                                   0,
                                   NULL,
                                   SQL_DRIVER_NOPROMPT);

            if (!SQL_SUCCEEDED(sqlRet))
            {
               Os::Logger::instance().log(FAC_ODBC, PRI_ERR,
                             "odbcConnect: Failed to connect %s, error code %d",
                             connectionString.data(), sqlRet);
               extract_error("SQLDriverConnect", handle->mConnectionHandle, SQL_HANDLE_DBC);

               SQLFreeHandle(SQL_HANDLE_DBC, handle->mConnectionHandle);
               SQLFreeHandle(SQL_HANDLE_ENV, handle->mEnvironmentHandle);
               delete handle;
               handle = NULL;
            }
            else
            {
               // Connected to database, now alloc a statement handle
               if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_STMT,
                                                handle->mConnectionHandle,
                                                &handle->mStatementHandle)))
               {
                  Os::Logger::instance().log(FAC_ODBC, PRI_ERR,
                                "odbcConnect: Failed to allocate "
                                "statement handle");
                  extract_error("SQLAllocHandle", handle->mStatementHandle, SQL_HANDLE_STMT);

                  // Disconnect from database
                  SQLDisconnect(handle->mConnectionHandle);
                  // Free resources

                  SQLFreeHandle(SQL_HANDLE_DBC, handle->mConnectionHandle);
                  SQLFreeHandle(SQL_HANDLE_ENV, handle->mEnvironmentHandle);
                  delete handle;
                  handle = NULL;
               }
               else
               {
                  Os::Logger::instance().log(FAC_ODBC, PRI_DEBUG,
                                "odbcConnect: Connected to database "
                                "%s, OdbcHandle %p",
                                connectionString.data(), handle);
                }
            }
         }
      }
   }
   else
   {
      Os::Logger::instance().log(FAC_ODBC, PRI_ERR,
                    "odbcConnect: Couldn't create OdbcHandle");
   }

   return handle;
}
Esempio n. 11
0
/*
---------------------------------------------------------
   TestSQLGetDescRec
---------------------------------------------------------
*/
PassFail TestMXSQLGetDescRec(TestInfo *pTestInfo)
{   
	TEST_DECLARE;
	RETCODE				returncode;
	SQLHANDLE 			henv;
	SQLHANDLE 			hdbc;
	SQLHANDLE			hstmt, hstmt1;
	
	//Common input params to the apis
	SQLHDESC			hIrd, hImArd, hImIrd, hImApd, hImIpd, hExArd, hExApd;
	SWORD				RecNumber = 0;

	//SQLGetDescRec: params
	SQLHDESC			getDescRecHandle;				//input
	SWORD				getDescRecNumber;				//input
	TCHAR				getDescName[MAXLEN];		 
	SWORD				getNameMaxLength;				//input; MAXLEN = 100 : defined in Common.h
	SWORD				getDescNameActualLength;
	SQLSMALLINT			getDescType;
	SWORD				getDescIntervalCode;
	SQLLEN				getDescOctectLength; 
	SWORD				getDescPrecision;
	SWORD				getDescScale;
	SWORD				getDescNullable;

	//SQLSetDescRec: params
	SQLHDESC			setDescRecHandle;
	SQLSMALLINT			setDescRecNumber;
	SQLSMALLINT			setDescType;
	SQLSMALLINT			setDescIntervalCode;
	SQLINTEGER			setDescOctetLength;
	SQLSMALLINT			setDescPrecision;
	SQLSMALLINT			setDescScale;
	SQLPOINTER			setDescDataPtr;
	SQLLEN				setDescOctectLengthPtr; 
	SQLLEN				setDescIndicatorPtr; 

	TCHAR				setDescName[1];
	
	SQLINTEGER			setDescNullable = SQL_NULL_DATA;
	short int			i;

	// Template for a Descriptor record
	typedef struct {
	  //	TCHAR				DescName[MAXLEN];
	TCHAR				*DescName;
	short int			DescType;
	short int			DescDatetimeIntervalCode;
	short int			DescOctetLength;
	short int			DescPrecision;
	short int			DescScale;
	void*				DescDataPtr;
	short int			DescOctectLengthPtr;
	short int			DescIndicatorPtr;
	short int			DescNullable;
	}DescRec;

	DescRec TestDataAPD[DATA_ARR_LEN] = 
	{
	//APD
	//	DescName		Type				DatetimeIntervalCode	DescOctetLength		Precision	DescScale	DescDataPtr		OctectLengthPtr		IndicatorPtr				DescNullable
		{_T(""),			SQL_C_DEFAULT,				0,						0,				0,			0,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_TCHAR,					0,						80,				0,			0,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_TCHAR,					0,						300,			0,			0,			NULL,		SQL_NTS,			SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_NUMERIC,				0,						0,				0,			0,			NULL,		SQL_DATA_AT_EXEC,	SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_TYPE_TIMESTAMP,	SQL_CODE_TIMESTAMP,			0,				6,			1,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_INTERVAL_SECOND,	SQL_CODE_SECOND,			0,				2,			0,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN }
	};

	DescRec TestDataARD[DATA_ARR_LEN] =
	{
	//ARD
	//	DescName		Type				DatetimeIntervalCode	DescOctetLength		Precision	DescScale	DescDataPtr		OctectLengthPtr		IndicatorPtr				DescNullable
		{_T(""),			SQL_C_DEFAULT,				0,						0,				0,			0,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_TCHAR,					0,						80,				0,			0,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_TCHAR,					0,						300,			0,			0,			NULL,		SQL_NTS,			SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_NUMERIC,				0,						0,				0,			0,			NULL,		SQL_DATA_AT_EXEC,	SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_TYPE_TIMESTAMP,	SQL_CODE_TIMESTAMP,			0,				6,			1,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_INTERVAL_SECOND,	SQL_CODE_SECOND,			0,				2,			0,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN }
	};

	DescRec TestDataIPD[DATA_ARR_LEN] =
	{
	//IPD
	//	DescName		Type				DatetimeIntervalCode	DescOctetLength		Precision	DescScale	DescDataPtr		OctectLengthPtr		IndicatorPtr				DescNullable
		{_T(""),			SQL_C_DEFAULT,				0,						0,				0,			0,			0,				0,					0,					SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_TCHAR,					0,						80,				0,			0,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_TCHAR,					0,						300,			0,			0,			NULL,		SQL_NTS,			SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_NUMERIC,				0,						0,				0,			0,			NULL,		SQL_DATA_AT_EXEC,	SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_TYPE_TIMESTAMP,		SQL_CODE_TIMESTAMP,			0,				6,			1,			0,				0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_INTERVAL_SECOND,	SQL_CODE_SECOND,			0,				2,			0,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN }
	};

	DescRec TestDataIRD[DATA_ARR_LEN] =
	{
	//IRD can only be read
	//	DescName		Type				DatetimeIntervalCode	DescOctetLength		Precision	DescScale	DescDataPtr		OctectLengthPtr		IndicatorPtr				DescNullable
		{_T(""),			SQL_C_DEFAULT,				0,						0,				0,			0,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_TCHAR,					0,						80,				0,			0,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_TCHAR,					0,						300,			0,			0,			NULL,		SQL_NTS,			SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_NUMERIC,				0,						0,				0,			0,			NULL,		SQL_DATA_AT_EXEC,	SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_TIMESTAMP,		SQL_CODE_TIMESTAMP,			0,				6,			1,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN },
		{_T(""),			SQL_C_INTERVAL_SECOND,	SQL_CODE_SECOND,			0,				2,			0,			NULL,			0,				SQL_NULL_DATA,			SQL_NULLABLE_UNKNOWN }
	};
	_tcscpy(setDescName, _T(""));
// ================================================================================================================
//		begin common test setup 
//==================================================================================================================
	LogMsg(LINEBEFORE+SHORTTIMESTAMP,_T("Begin testing API => SQLSetDescRec and SQLGetDescRec.\n"));
	TEST_INIT;

	if(!FullConnectWithOptions(pTestInfo, CONNECT_ODBC_VERSION_3))
	{
		LogMsg(NONE,_T("Unable to connect\n"));
		TEST_FAILED;
		TEST_RETURN;
	}
	
	henv = pTestInfo->henv;
 	hdbc = pTestInfo->hdbc;

	returncode = SQLAllocHandle(SQL_HANDLE_STMT, (SQLHANDLE)hdbc, &hstmt);	
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocHandle"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		FullDisconnect(pTestInfo);
		TEST_FAILED;
		TEST_RETURN;
	}

	//Explicit APD
	//allocate an Explicit APD desc
	returncode = SQLAllocHandle(SQL_HANDLE_DESC, (SQLHANDLE)hdbc, &hExApd);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocHandle to get explicit APD"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		FullDisconnect(pTestInfo);
		TEST_FAILED;
		TEST_RETURN;
	}	

	//Explicit ARD
	returncode = SQLAllocHandle(SQL_HANDLE_DESC, (SQLHANDLE)hdbc, &hExArd);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocHandle to get explicit ARD"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		FullDisconnect(pTestInfo);
		TEST_FAILED;
		TEST_RETURN;
	}

//===============================================================================================================
//			Begin Testing:Positive Test for Implicit APD 
//===============================================================================================================	
	//Get Implicit APD handle
	returncode = SQLGetStmtAttr(hstmt, SQL_ATTR_APP_PARAM_DESC, &hImApd, 0, NULL);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetStmtAttr: get APD"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		LogMsg(ERRMSG,_T("Cannot allocate descriptor: Aborting Implicit APD tests.\n"));
		TEST_FAILED;
		goto ExAPDtests;		// transfers control to the next set of tests
	}

	for (i = 0;i < DATA_ARR_LEN; i++)		// i = index to TestDataAPD
	{
		TESTCASE_BEGIN("Test the positive functionality of SQLSetDescRec and SQLGetDescRec for Implicit APD.\n");


		//set multiple Fields
		RecNumber = i + 1;		//increment the recnumber and thus set the next rec (change SQL_DESC_COUNT)
		
		setDescRecHandle		= hImApd ;
		setDescRecNumber		= RecNumber;
		setDescType				= TestDataAPD[i].DescType; 
		setDescIntervalCode		= TestDataAPD[i].DescDatetimeIntervalCode;
		setDescOctetLength		= TestDataAPD[i].DescOctetLength;	
		setDescPrecision		= TestDataAPD[i].DescPrecision;	
		setDescScale			= TestDataAPD[i].DescScale;	
		setDescDataPtr			= TestDataAPD[i].DescDataPtr;			
		setDescOctectLengthPtr	= TestDataAPD[i].DescOctectLengthPtr;			
		setDescIndicatorPtr		= TestDataAPD[i].DescIndicatorPtr;	

		/*LogMsg(NONE,_T("SQLSetDescRec(handle,%d,%d,%d,%d,%d,%d,%s,%d,%d)\n"),
											setDescRecNumber, 
											setDescType, 
											setDescIntervalCode, 
											setDescOctetLength , 
											setDescPrecision, 
											setDescScale, 
											setDescDataPtr,
											setDescOctectLengthPtr, 
											setDescIndicatorPtr);  */

		returncode = SQLSetDescRec(setDescRecHandle, setDescRecNumber, setDescType, setDescIntervalCode, setDescOctetLength , setDescPrecision, setDescScale, setDescDataPtr,&setDescOctectLengthPtr, &setDescIndicatorPtr);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetDescRec "))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG,_T("SQLSetDescRec: positive tests for Implicit APD: TestDataAPD['%d'].\n"),i);
			//FullDisconnect(pTestInfo);
			TEST_FAILED;
			//TEST_RETURN;
			continue;
		}
		
		//Get the Implicit APD Descriptor 
		//LogMsg(SHORTTIMESTAMP,"SQLGetDescRec: test for Implicit APD.\n");
		LogMsg(NONE,_T("SQLSetDescRec / SQLGetDescRec: positive tests for Implicit APD.\n"));


		getDescRecHandle		= hImApd;					
		getDescRecNumber		= RecNumber;				
		getNameMaxLength		= MAXLEN;
		_tcscpy(getDescName	,_T(""));	//initialize
		setDescNullable			= TestDataAPD[i].DescNullable;

		returncode = SQLGetDescRec(getDescRecHandle, getDescRecNumber, (SQLTCHAR*)getDescName, getNameMaxLength, &getDescNameActualLength, &getDescType, &getDescIntervalCode, &getDescOctectLength, &getDescPrecision, &getDescScale, &getDescNullable);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetDescRec"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG,_T("SQLGetDescRec: positive tests for Implicit APD: TestDataAPD['%d'].\n"),i);
			//FullDisconnect(pTestInfo);
			TEST_FAILED;
			//TEST_RETURN;
			continue;
		}

		//begin checking  APD values ----------
		
		//check  SQL_DESC_NAME
		if (!(_tcscmp(getDescName, setDescName)))
		{
			LogMsg(NONE,_T("SQL_DESC_NAME value returned is '%s'\n"),getDescName);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NAME: '%s' and actual: '%s' are not matched\n"), setDescName,getDescName);
		}
		
		//check SQL_DESC_TYPE
		if (getDescType == setDescType)
		{
			LogMsg(NONE,_T("SQL_DESC_TYPE value returned is '%d'\n"),getDescType);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_TYPE: '%d' and actual: '%d' are not matched\n"), setDescType, getDescType);
		}

		//check SQL_DESC_DATETIME_INTERVAL_CODE
		if (getDescIntervalCode == setDescIntervalCode)
		{
			LogMsg(NONE,_T("SQL_DESC_DATETIME_INTERVAL_CODE value returned is '%d'\n"),getDescIntervalCode);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_DATETIME_INTERVAL_CODE: '%d' and actual: '%d' are not matched\n"), setDescIntervalCode, getDescIntervalCode);
		}
		//check SQL_DESC_OCTECT_LENGTH
		if (getDescOctectLength == setDescOctetLength)
		{
			LogMsg(NONE,_T("SQL_DESC_OCTECT_LENGTH value returned is '%d'\n"),getDescOctectLength);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_OCTECT_LENGTH: '%d' and actual: '%d' are not matched\n"), setDescOctetLength,getDescOctectLength);
		}

		//check SQL_DESC_PRECISION
		if (getDescPrecision == setDescPrecision)
		{
			LogMsg(NONE,_T("SQL_DESC_PRECISION value returned is '%d'\n"),getDescPrecision);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_PRECISION: '%d' and actual: '%d' are not matched\n"), setDescPrecision,getDescPrecision);
		}

		//check SQL_DESC_SCALE
		if (getDescScale == setDescScale)
		{
			LogMsg(NONE,_T("SQL_DESC_SCALE value returned is '%d'\n"),getDescScale);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_SCALE: '%d' and actual: '%d' are not matched\n"), setDescScale,getDescScale);
		}

		//check SQL_DESCNULLABLE
		if (getDescNullable == setDescNullable)
		{
			LogMsg(NONE,_T("SQL_DESC_NULLABLE value returned is '%d'\n"),getDescNullable);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NULLABLE: '%d' and actual: '%d' are not matched\n"), setDescNullable, getDescNullable);
		}
		// end of checks 
		TESTCASE_END;

	} //end for loop; end of positive tests for APD
	 

//===============================================================================================================
//			Begin Testing:Positive Test for Explicit APD 
//===============================================================================================================
	ExAPDtests: ;		// beginning next set of tests
	
	//mark the beginning of tests in log file
	//LogMsg(SHORTTIMESTAMP, "Test the positive functionality of SQLSetDescRec and SQLGetDescRec for Explicit APD.\n");
	
	//Get Explicit APD handle
	returncode = SQLAllocHandle(SQL_HANDLE_DESC, (SQLHANDLE)hdbc, &hExApd);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocHandle: get Explicit APD"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		LogMsg(ERRMSG,_T("Cannot allocate descriptor: Aborting Explicit APD tests.\n"));
		TEST_FAILED;
		//TEST_RETURN;
		goto ARDtests;		// transfers control to the next set of tests
	}

	//associate with a statement
	returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_APP_PARAM_DESC, (SQLPOINTER)hExApd, SQL_IS_POINTER);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetStmtAttr: explicit APD"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		LogMsg(ERRMSG, _T("Cannot set Explicit APD for statement.\n"));
		TEST_FAILED;
	}

	setDescRecHandle = hExApd ;

	for (i = 0;i < DATA_ARR_LEN; i++)		// i = index to TestDataAPD
	{
		TESTCASE_BEGIN("Test the positive functionality of SQLSetDescRec and SQLGetDescRec for Explicit APD.\n");


		//set multiple Fields
		RecNumber = i + 1;		//increment the recnumber and thus set the next rec (change SQL_DESC_COUNT)
		

		setDescRecNumber		= RecNumber;
		setDescType				= TestDataAPD[i].DescType; 
		setDescIntervalCode		= TestDataAPD[i].DescDatetimeIntervalCode;
		setDescOctetLength		= TestDataAPD[i].DescOctetLength;	
		setDescPrecision		= TestDataAPD[i].DescPrecision;	
		setDescScale			= TestDataAPD[i].DescScale;	
		setDescDataPtr			= TestDataAPD[i].DescDataPtr;			
		setDescOctectLengthPtr	= TestDataAPD[i].DescOctectLengthPtr;			
		setDescIndicatorPtr		= TestDataAPD[i].DescIndicatorPtr;	


		/*LogMsg(NONE,_T("SQLSetDescRect(handle,%d,%d,%d,%d,%d,%d,%s,%d,%d)\n"),
									setDescRecNumber, 
									setDescType, 
									setDescIntervalCode, 
									setDescOctetLength , 
									setDescPrecision, 
									setDescScale, 
									setDescDataPtr,
									setDescOctectLengthPtr, 
									setDescIndicatorPtr);*/

		returncode = SQLSetDescRec(setDescRecHandle, setDescRecNumber, setDescType, setDescIntervalCode, setDescOctetLength , setDescPrecision, setDescScale, setDescDataPtr,&setDescOctectLengthPtr, &setDescIndicatorPtr);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetDescRec"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG,_T("SQLSetDescRec: positive tests for Explicit APD: TestDataAPD['%d'].\n"),i);
			TEST_FAILED;
			//TEST_RETURN;
			continue;
		}
		
			
		//Get the Explicit APD Descriptor 
		//LogMsg(SHORTTIMESTAMP,"SQLGetDescRec: test for Implicit APD.\n");
		LogMsg(NONE,_T("SQLSetDescRec / SQLGetDescRec: positive tests for Explicit APD.\n"));


		getDescRecHandle		= 	setDescRecHandle;					
		getDescRecNumber		= RecNumber;				
		getNameMaxLength		= MAXLEN;
		_tcscpy(getDescName	,_T(""));	//initialize		
		setDescNullable			= TestDataAPD[i].DescNullable;

		returncode = SQLGetDescRec(getDescRecHandle, getDescRecNumber, (SQLTCHAR*)getDescName, getNameMaxLength, &getDescNameActualLength, &getDescType, &getDescIntervalCode, &getDescOctectLength, &getDescPrecision, &getDescScale, &getDescNullable);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetDescRec and SQLGetDescRec"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG,_T("SQLGetDescRec: positive tests for Explicit APD: TestDataAPD['%d'].\n"),i);
			TEST_FAILED;
			continue;
		}

		//begin checking  APD values 
		
		//check  SQL_DESC_NAME
		if (!(_tcscmp(getDescName, setDescName)))
		{
			LogMsg(NONE,_T("SQL_DESC_NAME value returned is '%s'\n"),getDescName);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NAME: '%s' and actual: '%s' are not matched\n"), setDescName,getDescName);
		}
		
		//check SQL_DESC_TYPE
		if (getDescType == setDescType)
		{
			LogMsg(NONE,_T("SQL_DESC_TYPE value returned is '%d'\n"),getDescType);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_TYPE: '%d' and actual: '%d' are not matched\n"), setDescType, getDescType);
		}

		//check SQL_DESC_DATETIME_INTERVAL_CODE
		if (getDescIntervalCode == setDescIntervalCode)
		{
			LogMsg(NONE,_T("SQL_DESC_DATETIME_INTERVAL_CODE value returned is '%d'\n"),getDescIntervalCode);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_DATETIME_INTERVAL_CODE: '%d' and actual: '%d' are not matched\n"), setDescIntervalCode, getDescIntervalCode);
		}
		//check SQL_DESC_OCTECT_LENGTH
		if (getDescOctectLength == setDescOctetLength)
		{
			LogMsg(NONE,_T("SQL_DESC_OCTECT_LENGTH value returned is '%d'\n"),getDescOctectLength);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_OCTECT_LENGTH: '%d' and actual: '%d' are not matched\n"), setDescOctetLength,getDescOctectLength);
		}

		//check SQL_DESC_PRECISION
		if (getDescPrecision == setDescPrecision)
		{
			LogMsg(NONE,_T("SQL_DESC_PRECISION value returned is '%d'\n"),getDescPrecision);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_PRECISION: '%d' and actual: '%d' are not matched\n"), setDescPrecision,getDescPrecision);
		}

		//check SQL_DESC_SCALE
		if (getDescScale == setDescScale)
		{
			LogMsg(NONE,_T("SQL_DESC_SCALE value returned is '%d'\n"),getDescScale);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_SCALE: '%d' and actual: '%d' are not matched\n"), setDescScale,getDescScale);
		}

		//check SQL_DESCNULLABLE
		if (getDescNullable == setDescNullable)
		{
			LogMsg(NONE,_T("SQL_DESC_NULLABLE value returned is '%d'\n"),getDescNullable);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NULLABLE: '%d' and actual: '%d' are not matched\n"), setDescNullable, getDescNullable);
		}
		// end of checks 


		
		TESTCASE_END;

	} //end for loop; end of positive tests for Explicit APD


	 
//===============================================================================================================
//			Begin Testing: Statement reverts to Implicit APD after freeing Explicit Descriptor
//===============================================================================================================
	
	//mark the beginning of tests in log file
	//LogMsg(SHORTTIMESTAMP, "SQLGetDescRec for Explicit-Implicit APD: statement reverts to implicit descriptor after explicit descriptor has been freed.\n");
	
	//free Explicit APD
	returncode = SQLFreeHandle(SQL_HANDLE_DESC, hExApd);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFreeHandle (for APD)"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		LogMsg(ERRMSG,_T("Cannot free explicit descriptor: Aborting Explicit-Implicit Descriptor tests.\n"));
		TEST_FAILED;
		goto ARDtests;		// transfers control to the next set of tests
	}

	//Use the previously allocated Implicit APD handle
	getDescRecHandle		= hImApd;

		TESTCASE_BEGIN("Test that the implicit descriptor get associated with statement after explicit descriptor has been freed.\n");


		//set multiple Fields
		i			= 0;
		RecNumber = i + 1;		//increment the recnumber and thus set the next rec (change SQL_DESC_COUNT)
		
		
		setDescRecNumber		= RecNumber;
		setDescType				= TestDataAPD[i].DescType; 
		setDescIntervalCode		= TestDataAPD[i].DescDatetimeIntervalCode;
		setDescOctetLength		= TestDataAPD[i].DescOctetLength;	
		setDescPrecision		= TestDataAPD[i].DescPrecision;	
		setDescScale			= TestDataAPD[i].DescScale;	
		setDescDataPtr			= TestDataAPD[i].DescDataPtr;			
		setDescOctectLengthPtr	= TestDataAPD[i].DescOctectLengthPtr;			
		setDescIndicatorPtr		= TestDataAPD[i].DescIndicatorPtr;	

			
		//Get the Implicit APD Descriptor 
		LogMsg(NONE,_T("SQLGetDescRec: tests for Explicit-Implicit Descriptor.\n"));
			
		getDescRecNumber		= RecNumber;				
		getNameMaxLength		= MAXLEN;
		_tcscpy(getDescName	,_T(""));	//initialize		
		setDescNullable			= TestDataAPD[i].DescNullable;

		returncode = SQLGetDescRec(getDescRecHandle, getDescRecNumber, (SQLTCHAR*)getDescName, getNameMaxLength, &getDescNameActualLength, &getDescType, &getDescIntervalCode, &getDescOctectLength, &getDescPrecision, &getDescScale, &getDescNullable);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetDescRec"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG,_T("SQLGetDescRec: tests for Explicit-Implicit APD: TestDataAPD['%d'].\n"),i);
			TEST_FAILED;
			//continue;
		}

		//begin checking  APD values ----------
		
		//check  SQL_DESC_NAME
		if (!(_tcscmp(getDescName, setDescName)))
		{
			LogMsg(NONE,_T("SQL_DESC_NAME value returned is '%s'\n"),getDescName);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NAME: '%s' and actual: '%s' are not matched\n"), setDescName,getDescName);
		}
		
		//check SQL_DESC_TYPE
		if (getDescType == setDescType)
		{
			LogMsg(NONE,_T("SQL_DESC_TYPE value returned is '%d'\n"),getDescType);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_TYPE: '%d' and actual: '%d' are not matched\n"), setDescType, getDescType);
		}

		//check SQL_DESC_DATETIME_INTERVAL_CODE
		if (getDescIntervalCode == setDescIntervalCode)
		{
			LogMsg(NONE,_T("SQL_DESC_DATETIME_INTERVAL_CODE value returned is '%d'\n"),getDescIntervalCode);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_DATETIME_INTERVAL_CODE: '%d' and actual: '%d' are not matched\n"), setDescIntervalCode, getDescIntervalCode);
		}
		//check SQL_DESC_OCTECT_LENGTH
		if (getDescOctectLength == setDescOctetLength)
		{
			LogMsg(NONE,_T("SQL_DESC_OCTECT_LENGTH value returned is '%d'\n"),getDescOctectLength);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_OCTECT_LENGTH: '%d' and actual: '%d' are not matched\n"), setDescOctetLength,getDescOctectLength);
		}

		//check SQL_DESC_PRECISION
		if (getDescPrecision == setDescPrecision)
		{
			LogMsg(NONE,_T("SQL_DESC_PRECISION value returned is '%d'\n"),getDescPrecision);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_PRECISION: '%d' and actual: '%d' are not matched\n"), setDescPrecision,getDescPrecision);
		}

		//check SQL_DESC_SCALE
		if (getDescScale == setDescScale)
		{
			LogMsg(NONE,_T("SQL_DESC_SCALE value returned is '%d'\n"),getDescScale);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_SCALE: '%d' and actual: '%d' are not matched\n"), setDescScale,getDescScale);
		}

		//check SQL_DESCNULLABLE
		if (getDescNullable == setDescNullable)
		{
			LogMsg(NONE,_T("SQL_DESC_NULLABLE value returned is '%d'\n"),getDescNullable);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NULLABLE: '%d' and actual: '%d' are not matched\n"), setDescNullable, getDescNullable);
		}
		// end of checks 
		TESTCASE_END;




//==================================================================================================================
//		Begin Testing: Positive Test for Implicit ARD 
//===================================================================================================================
	ARDtests:	;
	
	//mark the beginning of tests in log file
	//LogMsg(SHORTTIMESTAMP, "Test the positive functionality of SQLSetDescRec and SQLGetDescRec for Implicit ARD.\n");
	

	//Get Implicit ARD handle
	returncode = SQLGetStmtAttr(hstmt, SQL_ATTR_APP_ROW_DESC, &hImArd, 0, NULL);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetStmtAttr: get ARD"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		LogMsg(ERRMSG, _T("Cannot get ARD: Aborting Implicit ARD tests.\n"));
		TEST_FAILED;
		goto ExARDtests;		//go to next set of tests
	}
				
	for (i = 0;i < DATA_ARR_LEN; i++)		// i = index to TestDataARD
	{
		TESTCASE_BEGIN("Test the positive functionality of SQLSetDescRec and SQLGetDescRec for Implicit ARD.\n");


		
		//set multiple Fields
		RecNumber = i + 1;		//increment the recnumber and thus set the next rec (change SQL_DESC_COUNT)
		
		setDescRecHandle		= hImArd ;
		setDescRecNumber		= RecNumber;
		setDescType				= TestDataARD[i].DescType; 
		setDescIntervalCode		= TestDataARD[i].DescDatetimeIntervalCode;	
		setDescOctetLength		= TestDataARD[i].DescOctetLength;	
		setDescPrecision		= TestDataARD[i].DescPrecision;	
		setDescScale			= TestDataARD[i].DescScale;		
		setDescDataPtr			= TestDataARD[i].DescDataPtr;			
		setDescOctectLengthPtr	= TestDataARD[i].DescOctectLengthPtr;			
		setDescIndicatorPtr		= TestDataARD[i].DescIndicatorPtr;				


		returncode = SQLSetDescRec(setDescRecHandle, setDescRecNumber, setDescType, setDescIntervalCode, setDescOctetLength , setDescPrecision, setDescScale, setDescDataPtr,&setDescOctectLengthPtr, &setDescIndicatorPtr);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetDescRec and SQLGetDescRec"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG,_T("SQLSetDescRec: positive tests for Implicit ARD: TestDataARD['%d'].\n"),i);
			//FullDisconnect(pTestInfo);
			TEST_FAILED;
			//TEST_RETURN;
			continue;
		}
		
			
		//Get the Implicit ARD Descriptor 
		LogMsg(NONE,_T("SQLSetDescRec / SQLGetDescRec: positive tests for Implicit ARD.\n"));

		getDescRecHandle		= hImApd;					
		getDescRecNumber		= RecNumber;				
		getNameMaxLength		= MAXLEN;
		_tcscpy(getDescName	,_T(""));	//initialize		
		setDescNullable			= TestDataARD[i].DescNullable;

		returncode = SQLGetDescRec(getDescRecHandle, getDescRecNumber, (SQLTCHAR*)getDescName, getNameMaxLength, &getDescNameActualLength, &getDescType, &getDescIntervalCode, &getDescOctectLength, &getDescPrecision, &getDescScale, &getDescNullable);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetDescRec and SQLGetDescRec"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG,_T("SQLGetDescRec: positive tests for Implicit ARD: TestDataARD['%d'].\n"),i);
			//FullDisconnect(pTestInfo);
			TEST_FAILED;
			//TEST_RETURN;
			break;
		}

		//begin checking  ARD values 
		
		//check  SQL_DESC_NAME
		if (!(_tcscmp(getDescName, setDescName)))
		{
			LogMsg(NONE,_T("SQL_DESC_NAME value returned is '%s'\n"),getDescName);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NAME: '%s' and actual: '%s' are not matched\n"), setDescName,getDescName);
		}
		
		//check SQL_DESC_TYPE
		if (getDescType == setDescType)
		{
			LogMsg(NONE,_T("SQL_DESC_TYPE value returned is '%d'\n"),getDescType);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_TYPE: '%d' and actual: '%d' are not matched\n"), setDescType, getDescType);
		}

		//check SQL_DESC_DATETIME_INTERVAL_CODE
		if (getDescIntervalCode == setDescIntervalCode)
		{
			LogMsg(NONE,_T("SQL_DESC_DATETIME_INTERVAL_CODE value returned is '%d'\n"),getDescIntervalCode);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_DATETIME_INTERVAL_CODE: '%d' and actual: '%d' are not matched\n"), setDescIntervalCode, getDescIntervalCode);
		}
		//check SQL_DESC_OCTECT_LENGTH
		if (getDescOctectLength == setDescOctetLength)
		{
			LogMsg(NONE,_T("SQL_DESC_OCTECT_LENGTH value returned is '%d'\n"),getDescOctectLength);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_OCTECT_LENGTH: '%d' and actual: '%d' are not matched\n"), setDescOctetLength,getDescOctectLength);
		}

		//check SQL_DESC_PRECISION
		if (getDescPrecision == setDescPrecision)
		{
			LogMsg(NONE,_T("SQL_DESC_PRECISION value returned is '%d'\n"),getDescPrecision);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_PRECISION: '%d' and actual: '%d' are not matched\n"), setDescPrecision,getDescPrecision);
		}

		//check SQL_DESC_SCALE
		if (getDescScale == setDescScale)
		{
			LogMsg(NONE,_T("SQL_DESC_SCALE value returned is '%d'\n"),getDescScale);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_SCALE: '%d' and actual: '%d' are not matched\n"), setDescScale,getDescScale);
		}

		//check SQL_DESCNULLABLE
		if (getDescNullable == setDescNullable)
		{
			LogMsg(NONE,_T("SQL_DESC_NULLABLE value returned is '%d'\n"),getDescNullable);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NULLABLE: '%d' and actual: '%d' are not matched\n"), setDescNullable, getDescNullable);
		}
		// end of checks
		TESTCASE_END;

	} //end for loop; end of positive tests for ARD
	


//==================================================================================================================
//		Begin Testing: Positive Test for Explicit ARD 
//===================================================================================================================
	ExARDtests:	;
	
	//mark the beginning of tests in log file
	//LogMsg(SHORTTIMESTAMP, "Test the positive functionality of SQLSetDescRec and SQLGetDescRec for Explicit ARD.\n");
	

	//Get Explicit ARD handle
	returncode = SQLAllocHandle(SQL_HANDLE_DESC, (SQLHANDLE)hdbc, &hExArd);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocHandle: get explicit ARD"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		LogMsg(ERRMSG, _T("Cannot get ARD: Aborting Implicit ARD tests.\n"));
		TEST_FAILED;
		goto IPDtests;		//go to next set of tests
	}

	//associate with a statement
	returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_APP_ROW_DESC, (SQLPOINTER)hExArd, SQL_IS_POINTER);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetStmtAttr: explicit ARD"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		LogMsg(ERRMSG, _T("Cannot set Explicit ARD for statement.\n"));
		TEST_FAILED;
	}

				
	for (i = 0;i < DATA_ARR_LEN; i++)		// i = index to TestDataARD
	{
		TESTCASE_BEGIN("Test the positive functionality of SQLSetDescRec and SQLGetDescRec for Explicit ARD.\n");


		
		//set multiple Fields
		RecNumber = i + 1;		//increment the recnumber and thus set the next rec (change SQL_DESC_COUNT)
		
		setDescRecHandle		= hExArd ;
		setDescRecNumber		= RecNumber;
		setDescType				= TestDataARD[i].DescType; 
		setDescIntervalCode		= TestDataARD[i].DescDatetimeIntervalCode;	
		setDescOctetLength		= TestDataARD[i].DescOctetLength;	
		setDescPrecision		= TestDataARD[i].DescPrecision;	
		setDescScale			= TestDataARD[i].DescScale;		
		setDescDataPtr			= TestDataARD[i].DescDataPtr;			
		setDescOctectLengthPtr	= TestDataARD[i].DescOctectLengthPtr;			
		setDescIndicatorPtr		= TestDataARD[i].DescIndicatorPtr;				


		returncode = SQLSetDescRec(setDescRecHandle, setDescRecNumber, setDescType, setDescIntervalCode, setDescOctetLength , setDescPrecision, setDescScale, setDescDataPtr,&setDescOctectLengthPtr, &setDescIndicatorPtr);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetDescRec"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG,_T("SQLSetDescRec: positive tests for Explicit ARD: TestDataARD['%d'].\n"),i);
			TEST_FAILED;
			continue;
		}
		
			
		//Get the Explicit ARD Descriptor 
		LogMsg(NONE,_T("SQLSetDescRec and SQLGetDescRec: positive tests for Explicit ARD.\n"));

		getDescRecHandle		= hExArd;					
		getDescRecNumber		= RecNumber;				
		getNameMaxLength		= MAXLEN;
		_tcscpy(getDescName	,_T(""));	//initialize		
		setDescNullable			= TestDataARD[i].DescNullable;

		returncode = SQLGetDescRec(getDescRecHandle, getDescRecNumber, (SQLTCHAR*)getDescName, getNameMaxLength, &getDescNameActualLength, &getDescType, &getDescIntervalCode, &getDescOctectLength, &getDescPrecision, &getDescScale, &getDescNullable);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetDescRec"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG,_T("SQLGetDescRec: positive tests for Explicit ARD: TestDataARD['%d'].\n"),i);
			TEST_FAILED;
			break;
		}

		//begin checking  ARD values 
		
		//check  SQL_DESC_NAME
		if (!(_tcscmp(getDescName, setDescName)))
		{
			LogMsg(NONE,_T("SQL_DESC_NAME value returned is '%s'\n"),getDescName);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NAME: '%s' and actual: '%s' are not matched\n"), setDescName,getDescName);
		}
		
		//check SQL_DESC_TYPE
		if (getDescType == setDescType)
		{
			LogMsg(NONE,_T("SQL_DESC_TYPE value returned is '%d'\n"),getDescType);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_TYPE: '%d' and actual: '%d' are not matched\n"), setDescType, getDescType);
		}

		//check SQL_DESC_DATETIME_INTERVAL_CODE
		if (getDescIntervalCode == setDescIntervalCode)
		{
			LogMsg(NONE,_T("SQL_DESC_DATETIME_INTERVAL_CODE value returned is '%d'\n"),getDescIntervalCode);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_DATETIME_INTERVAL_CODE: '%d' and actual: '%d' are not matched\n"), setDescIntervalCode, getDescIntervalCode);
		}
		//check SQL_DESC_OCTECT_LENGTH
		if (getDescOctectLength == setDescOctetLength)
		{
			LogMsg(NONE,_T("SQL_DESC_OCTECT_LENGTH value returned is '%d'\n"),getDescOctectLength);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_OCTECT_LENGTH: '%d' and actual: '%d' are not matched\n"), setDescOctetLength,getDescOctectLength);
		}

		//check SQL_DESC_PRECISION
		if (getDescPrecision == setDescPrecision)
		{
			LogMsg(NONE,_T("SQL_DESC_PRECISION value returned is '%d'\n"), getDescPrecision);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_PRECISION: '%d' and actual: '%d' are not matched\n"), setDescPrecision,getDescPrecision);
		}

		//check SQL_DESC_SCALE
		if (getDescScale == setDescScale)
		{
			LogMsg(NONE,_T("SQL_DESC_SCALE value returned is '%d'\n"),getDescScale);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_SCALE: '%d' and actual: '%d' are not matched\n"), setDescScale,getDescScale);
		}

		//check SQL_DESCNULLABLE
		if (getDescNullable == setDescNullable)
		{
			LogMsg(NONE,_T("SQL_DESC_NULLABLE value returned is '%d'\n"),getDescNullable);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NULLABLE: '%d' and actual: '%d' are not matched\n"), setDescNullable, getDescNullable);
		}
		// end of checks
		TESTCASE_END;

	} //end for loop; end of positive tests for Explicit ARD

	//free explicit ARD
	returncode = SQLFreeHandle(SQL_HANDLE_DESC, hExArd);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFreeHandle (for ARD)"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		TEST_FAILED;
	}
	

//======================================================================================================================
//		 Begin Testing: Positive Test for Implicit IPD 
//=====================================================================================================================	

	IPDtests:	;
	
	//mark the beginning of tests in log file
	//LogMsg(SHORTTIMESTAMP, "Test the positive functionality of SQLSetDescRec and SQLGetDescRec for Implicit IPD.\n");
	

	//Get Implicit IPD handle
	returncode = SQLGetStmtAttr(hstmt, SQL_ATTR_APP_ROW_DESC, &hImIpd, 0, NULL);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetStmtAttr: get IPD"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		LogMsg(ERRMSG, _T("Cannot get IPD: Aborting Implicit IPD tests.\n"));
		TEST_FAILED;
		goto IRDtests;		//go to next set of tests
	}	
	
	
	
	for (i = 0;i < DATA_ARR_LEN; i++)		// i = index to TestDataIPD
	{
		TESTCASE_BEGIN("Test the positive functionality of SQLSetDescRec and SQLGetDescRec for Implicit IPD.\n");
		

		
		//set multiple Fields
		RecNumber = i + 1;		//increment the recnumber and thus set the next rec (change SQL_DESC_COUNT)
		
		setDescRecHandle		= hImIpd ;
		setDescRecNumber		= RecNumber;
		setDescType				= TestDataIPD[i].DescType; 
		setDescIntervalCode		= TestDataIPD[i].DescDatetimeIntervalCode;
		setDescOctetLength		= TestDataIPD[i].DescOctetLength;
		setDescPrecision		= TestDataIPD[i].DescPrecision;	
		setDescScale			= TestDataIPD[i].DescScale;		
		setDescDataPtr			= TestDataIPD[i].DescDataPtr;			
		setDescOctectLengthPtr	= TestDataIPD[i].DescOctectLengthPtr;			
		setDescIndicatorPtr		= TestDataIPD[i].DescIndicatorPtr;				

		returncode = SQLSetDescRec(setDescRecHandle, setDescRecNumber, setDescType, setDescIntervalCode, setDescOctetLength , setDescPrecision, setDescScale, setDescDataPtr,&setDescOctectLengthPtr, &setDescIndicatorPtr);
		if(!CHECKRC(SQL_SUCCESS,returncode, "SQLSetDescRec and SQLGetDescRec"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG,_T("SQLSetDescRec: positive tests for Implicit IPD: TestDataIPD['%d'].\n"),i);
			//FullDisconnect(pTestInfo);
			TEST_FAILED;
			//TEST_RETURN;
			continue;
		}
		
			
		//Get the Implicit IPD Descriptor 
		LogMsg(NONE,_T("SQLSetDescRec and SQLGetDescRec: positive tests for Implicit IPD.\n"));


		getDescRecHandle		= hImApd;					
		getDescRecNumber		= RecNumber;				
		getNameMaxLength		= MAXLEN;
		_tcscpy(getDescName	,_T(""));	//initialize	
		setDescNullable			= TestDataIPD[i].DescNullable;

		returncode = SQLGetDescRec(getDescRecHandle, getDescRecNumber, (SQLTCHAR*)getDescName, getNameMaxLength, &getDescNameActualLength, &getDescType, &getDescIntervalCode, &getDescOctectLength, &getDescPrecision, &getDescScale, &getDescNullable);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetDescRec"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG,_T("SQLGetDescRec: positive tests for Implicit IPD: TestDataIPD['%d'].\n"),i);
			//FullDisconnect(pTestInfo);
			TEST_FAILED;
			//TEST_RETURN;
			continue;
		}

		//begin checking  IPD values 
		
		//check  SQL_DESC_NAME
		if (!(_tcscmp(getDescName, setDescName)))
		{
			LogMsg(NONE,_T("SQL_DESC_NAME value returned is '%s'\n"),getDescName);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NAME: '%s' and actual: '%s' are not matched\n"), setDescName,getDescName);
		}
		
		//check SQL_DESC_TYPE
		if (getDescType == setDescType)
		{
			LogMsg(NONE,_T("SQL_DESC_TYPE value returned is '%d'\n"), getDescType);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_TYPE: '%d' and actual: '%d' are not matched\n"), setDescType, getDescType);
		}

		//check SQL_DESC_DATETIME_INTERVAL_CODE
		if (getDescIntervalCode == setDescIntervalCode)
		{
			LogMsg(NONE,_T("SQL_DESC_DATETIME_INTERVAL_CODE value returned is '%d'\n"),getDescIntervalCode);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_DATETIME_INTERVAL_CODE: '%d' and actual: '%d' are not matched\n"), setDescIntervalCode, getDescIntervalCode);
		}
		//check SQL_DESC_OCTECT_LENGTH
		if (getDescOctectLength == setDescOctetLength)
		{
			LogMsg(NONE,_T("SQL_DESC_OCTECT_LENGTH value returned is '%d'\n"),getDescOctectLength);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_OCTECT_LENGTH: '%d' and actual: '%d' are not matched\n"), setDescOctetLength,getDescOctectLength);
		}

		//check SQL_DESC_PRECISION
		if (getDescPrecision == setDescPrecision)
		{
			LogMsg(NONE,_T("SQL_DESC_PRECISION value returned is '%d'\n"),getDescPrecision);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_PRECISION: '%d' and actual: '%d' are not matched\n"), setDescPrecision,getDescPrecision);
		}

		//check SQL_DESC_SCALE
		if (getDescScale == setDescScale)
		{
			LogMsg(NONE,_T("SQL_DESC_SCALE value returned is '%d'\n"),getDescScale);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_SCALE: '%d' and actual: '%d' are not matched\n"), setDescScale,getDescScale);
		}

		//check SQL_DESCNULLABLE
		if (getDescNullable == setDescNullable)
		{
			LogMsg(NONE,_T("SQL_DESC_NULLABLE value returned is '%d'\n"),getDescNullable);
		}
		else
		{
			TEST_FAILED;					
			LogMsg(ERRMSG, _T("expect SQL_DESC_NULLABLE: '%d' and actual: '%d' are not matched\n"), setDescNullable, getDescNullable);
		}
		// end of checks 
		TESTCASE_END;

	} //end for loop; end of positive tests for IPD


//==================================================================================================================
//		 Begin Testing: Posituve Tests for IRD (IRD Desc Fields are read only) 
//==================================================================================================================
		IRDtests: ;

		//mark the beginning of tests in log file
		//LogMsg(SHORTTIMESTAMP, "Test the positive functionality of SQLSetDescRec and SQLGetDescRec for Implicit IRD.\n");
	
		//Get Implicit IRD handle
		returncode = SQLGetStmtAttr(hstmt, SQL_ATTR_IMP_ROW_DESC, &hImIrd, 0, NULL);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetStmtAttr"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			LogMsg(ERRMSG, _T("Cannot get IRD: Aborting Implicit IRD tests.\n"));
			TEST_FAILED;
		//	TEST_RETURN;		//this will abort tests and perform a full disconnect.
		}

		//---------------------------------------------------------------------------------------------------------
		
		TESTCASE_BEGIN("Test SQLSetDescRec for Implicit IRD: IRD Descriptor Fields cannot be set by the application.\n");
		
		//set multiple Fields
		RecNumber = i + 1;		//increment the recnumber and thus set the next rec (change SQL_DESC_COUNT)
		
		setDescRecHandle		= hImIrd ;
		setDescRecNumber		= RecNumber;
		setDescType				= TestDataIRD[i].DescType; 
		setDescIntervalCode		= TestDataIRD[i].DescDatetimeIntervalCode;	
		setDescOctetLength		= TestDataIRD[i].DescOctetLength;	
		setDescPrecision		= TestDataIRD[i].DescPrecision;	
		setDescScale			= TestDataIRD[i].DescScale;		
		setDescDataPtr			= TestDataIRD[i].DescDataPtr;			
		setDescOctectLengthPtr	= TestDataIRD[i].DescOctectLengthPtr;			
		setDescIndicatorPtr		= TestDataIRD[i].DescIndicatorPtr;				

		returncode = SQLSetDescRec(setDescRecHandle, setDescRecNumber, setDescType, setDescIntervalCode, setDescOctetLength , setDescPrecision, setDescScale, setDescDataPtr,&setDescOctectLengthPtr, &setDescIndicatorPtr);
		if(!CHECKRC(SQL_ERROR,returncode,"SQLSetDescRec"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			TEST_FAILED;

		}
		TESTCASE_END;
		
		//-------------------------------------------------------------------------------------------------------------
		
		TESTCASE_BEGIN("Test SQLGetDescRec for Implicit IRD: IRD Descriptor Fields not populated before call to DB.\n");
		
		//This testcases use the Implicit IRD handle obtained in previous testcase

		returncode = SQLGetDescRec(hImIrd, 1, (SQLTCHAR*)getDescName, MAXLEN, &getDescNameActualLength, &getDescType, &getDescIntervalCode, &getDescOctectLength, &getDescPrecision, &getDescScale, &getDescNullable);
		if(!CHECKRC(SQL_NO_DATA_FOUND,returncode,"SQLGetDescField"))
		{
			LogAllErrorsVer3(henv,hdbc,hstmt);
			TEST_FAILED;
			//TEST_RETURN;	//last test: valid to use TEST_RETURN when the test suite must be exited.
		}

		TESTCASE_END;

//===============================================================================================================
//			Begin Testing:Positive Test for populated Implicit IRD 
//===============================================================================================================

	TESTCASE_BEGIN("Test SQLGetDescRec for populated Implicit IRD.\n");

	//mark the beginning of tests in log file
	//LogMsg(SHORTTIMESTAMP, "Test the positive functionality of (SQLSetDescRec) and SQLGetDescRec for Implicit IRD.\n");
	
	//alloc new handle
	returncode = SQLAllocHandle(SQL_HANDLE_STMT, (SQLHANDLE)hdbc, &hstmt1);	
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocHandle"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt1);
		LogMsg(ERRMSG,_T("Cannot allocate statement: Aborting populated Implicit IRD tests.\n"));
		FullDisconnect(pTestInfo);
		TEST_FAILED;
		goto Cleanup;		// transfers control to the next set 
	}

	//Get Implicit IRD handle
	returncode = SQLGetStmtAttr(hstmt, SQL_ATTR_APP_PARAM_DESC, &hIrd, 0, NULL);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetStmtAttr: get IRD"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt1);
		LogMsg(ERRMSG,_T("Cannot allocate descriptor: Aborting populated Implicit IRD tests.\n"));
		TEST_FAILED;
		goto Cleanup;		// transfers control to the next set 
	}

	//populate the IRD by executing an catalog api
	returncode = SQLGetTypeInfo(hstmt1, SQL_ALL_TYPES);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetTypeInfo: population of IRD"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt1);
		LogMsg(ERRMSG,_T("Cannot execute statement: Aborting populated Implicit IRD tests.\n"));
		TEST_FAILED;
		goto Cleanup;		// transfers control to the next set 
	}	

	//check IRD
	returncode = SQLGetDescRec(hIrd, 1, (SQLTCHAR*)getDescName, MAXLEN, &getDescNameActualLength, &getDescType, &getDescIntervalCode, &getDescOctectLength, &getDescPrecision, &getDescScale, &getDescNullable);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetDescField"))
	{
			LogAllErrorsVer3(henv,hdbc,hstmt1);
			TEST_FAILED;
			//TEST_RETURN;	//last test: valid to use TEST_RETURN when the test suite must be exited.
	}
	
	TESTCASE_END;

	// free implicitly allocated descriptors by freeing statement
	returncode = SQLFreeHandle(SQL_HANDLE_STMT,hstmt1);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFreeHandle"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt1);
		TEST_FAILED;
	}

//===========================================================================================================
//		begin cleanup 
//==============================================================================================================
Cleanup: ;
		
	// free implicitly allocated descriptors by freeing statement
	returncode = SQLFreeHandle(SQL_HANDLE_STMT,hstmt);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFreeHandle"))
	{
		LogAllErrorsVer3(henv,hdbc,hstmt);
		TEST_FAILED;
	}
	

	
	FullDisconnect3(pTestInfo);
	LogMsg(SHORTTIMESTAMP+LINEAFTER,_T("End testing API => SQLSetDescRec and SQLGetDescRec.\n"));
    TEST_RETURN;
} //end of test ****************
Esempio n. 12
0
//*************************************************************************
int main()
{
  SQLHENV env;
  SQLHDBC dbc;
  SQLHSTMT stmt;
  SQLRETURN ret;
  SQLCHAR outstr[1024];
  SQLSMALLINT outstrlen;
  
  // Aloocate an environment handle
  ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env);
  checkrc(ret,__LINE__);
  
   //we need odbc3 support
   SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);
   
  //ALLOCATE A Connection handle
  ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc);
  checkrc(ret,__LINE__);
    
  // connect to the Data source
   ret = SQLConnect (dbc,
                   (SQLCHAR *) "DSN=mycsql;MODE=ADAPTER;SERVER=127.0.0.1;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=ADAPTER;SERVER=127.0.0.1;PORT=5678;"),
                   (SQLCHAR *) "root",
                   (SQLSMALLINT) strlen ("root"),
                   (SQLCHAR *) "manager",
                   (SQLSMALLINT) strlen (""));


  if(SQL_SUCCEEDED(ret))
  {
     printf("\nConnected to the Data Source..\n");
     
  }  
     
  
   else
   {
        printf("error in connection\n");
        ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
        checkrc(ret,__LINE__);

        ret = SQLFreeHandle(SQL_HANDLE_DBC,env);
        checkrc(ret,__LINE__);
        return 1;
   }
   //*********************************************************************
   //again call to driver connect
    
   ret = SQLConnect (dbc,
                   (SQLCHAR *) "DSN=mycsql;MODE=ADAPTER;SERVER=127.0.0.1;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=ADAPTER;SERVER=127.0.0.1;PORT=5678;"),
                   (SQLCHAR *) "root",
                   (SQLSMALLINT) strlen ("root"),
                   (SQLCHAR *) "manager",
                   (SQLSMALLINT) strlen (""));

   int rettype = ret; 

  if(SQL_SUCCEEDED(ret))
  {
     printf("\nConnected to the Data Source..\n");
     
             
   }

  
   else
   {
        printf("Connection name  in use\n");
    }

   //**********************************************************************
   ret = SQLDisconnect(dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
   checkrc(ret,__LINE__);
   if(rettype ==0)return 1;
   return 0;
}         
Esempio n. 13
0
/*
------------------------------------------------------------------
   TestSQLGetTypeInfo: Tests SQLGetTypeInfo                      
------------------------------------------------------------------
*/
PassFail TestSQLGetTypeInfoR18(TestInfo *pTestInfo)
{   
	TEST_DECLARE;
	char				Heading[MAX_STRING_SIZE];
  RETCODE			returncode;
  SQLHANDLE 			henv;
  SQLHANDLE 			hdbc;
  SQLHANDLE			hstmt;				  
  char				TempBuf[MAX_STRING_SIZE];	
  int				j = 0,END_LOOP;

	struct
	{
		char		*TYPE_NAME;
		SWORD		DATA_TYPE;
		SDWORD		PRECISION;
		char		*LITERAL_PREFIX;
		char		*LITERAL_SUFFIX;
		char		*CREATE_PARAMS;
		SWORD		NULLABLE;
		SWORD		CASE_SENSITIVE;
		SWORD		SEARCHABLE;
		SWORD		UNSIGNED_ATTRIBUTE;
		SWORD		MONEY;
		SWORD		AUTO_INCREMENT;
		char		*LOCAL_TYPE_NAME;
		SWORD		MINIMUM_SCALE;
		SWORD		MAXIMUM_SCALE;
	}	TypeInfo[] = 
		{//TYPENAME,DATATYPE,PREC,LITPRE,LITSUF,PARAM,NULL,CASE,SRCH,ATTR,MON,INC,LOC,MIN,MAX
			{"",SQL_ALL_TYPES,0,"","","",0,0,0,0,0,0,"",0,0},	// this is for get all types
			{"CHAR", SQL_CHAR, 254, "'", "'", "max length", SQL_NULLABLE, 1, SQL_SEARCHABLE, 0, 0, 0, "CHARACTER", 0, 0},
			{"VARCHAR", SQL_VARCHAR, 254, "'", "'", "max length", SQL_NULLABLE, 1, SQL_SEARCHABLE, 0, 0, 0, "VARCHAR", 0, 0},
			{"DECIMAL", SQL_DECIMAL, 18, "", "", "precision,scale", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "DECIMAL", 0, 18},
			{"NUMERIC", SQL_NUMERIC, 128, "", "", "precision,scale", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "NUMERIC", 0, 128},
			{"SMALLINT", SQL_SMALLINT, 5, "", "", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "SMALLINT", 0, 0},
			{"INTEGER", SQL_INTEGER, 10, "", "", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTEGER", 0, 0},
			{"REAL", SQL_REAL, 7, "", "", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "REAL", 0, 0},
			{"FLOAT", SQL_FLOAT, 15, "", "", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "FLOAT", 0, 0},
			{"DOUBLE PRECISION", SQL_DOUBLE, 15, "", "", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "DOUBLE", 0, 0},
//			{"DATE", SQL_DATE,  10,  "{d '",  "'}","", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "DATE", 0, 0},
//			{"TIME", SQL_TIME, 8, "{t '", "'}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "TIME", 0, 0},
//			{"TIMESTAMP", SQL_TIMESTAMP, 23, "{ts '", "'}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "TIMESTAMP", 0, 6},
			{"DATE", SQL_TYPE_DATE,  10,  "{d '",  "'}","", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "DATE", 0, 0},
			{"TIME", SQL_TYPE_TIME, 8, "{t '", "'}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "TIME", 0, 0},
			{"TIMESTAMP", SQL_TYPE_TIMESTAMP, 26, "{ts '", "'}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "TIMESTAMP", 0, 6},
			{"BIGINT", SQL_BIGINT, 19, "", "", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "LARGEINT", 0, 0},
			{"LONG VARCHAR", SQL_LONGVARCHAR, 4018, "'", "'", "", SQL_NULLABLE, 1, SQL_SEARCHABLE, 0, 0, 0, "LONG VARCHAR", 0, 0},
//			{"BINARY", SQL_BINARY, 4059, "'", "'", "max length", 1, 0, 0, 0, 0, 0, "", 0, 0},
//			{"VARBINARY", -3, 4059, "'", "'", "max length", 1, 0, 0, 0, 0, 0, "", 0, 0},
//			{"LONG VARBINARY", -4, 4059, "'", "'", "max length", 1, 0, 0, 0, 0, 0, "", 0, 0},
//			{"TINYINT", -6, 3, "", "", "", 1, 0, SQL_ALL_EXCEPT_LIKE, 1, 0, 0, "", 0, 0},
//			{"BIT", -7, 1, "", "", "", 1, 0, SQL_UNSEARCHABLE, 0, 0, 0, "", 0, 0},
			{"INTERVAL", SQL_INTERVAL_YEAR, 0, "{INTERVAL '", "' YEAR}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_MONTH, 0, "{INTERVAL '", "' MONTH}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_DAY, 0, "{INTERVAL '", "' DAY}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_HOUR, 0, "{INTERVAL '", "' HOUR}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_MINUTE, 0, "{INTERVAL '", "' MINUTE}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_SECOND, 0, "{INTERVAL '", "' SECOND}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_YEAR_TO_MONTH, 0, "{INTERVAL '", "' YEAR TO MONTH}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_DAY_TO_HOUR, 0, "{INTERVAL '", "' DAY TO HOUR}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_DAY_TO_MINUTE, 0, "{INTERVAL '", "' DAY TO MINUTE}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_DAY_TO_SECOND, 0, "{INTERVAL '", "' DAY TO SECOND}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_HOUR_TO_MINUTE, 0, "{INTERVAL '", "' HOUR TO MINUTE}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_HOUR_TO_SECOND, 0, "{INTERVAL '", "' HOUR TO SECOND}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"INTERVAL", SQL_INTERVAL_MINUTE_TO_SECOND, 0, "{INTERVAL '", "' MINUTE TO SECOND}", "", SQL_NULLABLE, 0, SQL_ALL_EXCEPT_LIKE, 0, 0, 0, "INTERVAL", 0, 0},
			{"",999,}	
	};



		char		oTYPE_NAME[TYPE_LEN];
		SWORD		oDATA_TYPE, fSqlType1;
		SDWORD		oPRECISION;
		char		oLITERAL_PREFIX[TYPE_LEN];
		char		oLITERAL_SUFFIX[TYPE_LEN];
		char		oCREATE_PARAMS[TYPE_LEN];
		SWORD		oNULLABLE;
		SWORD		oCASE_SENSITIVE;
		SWORD		oSEARCHABLE;
		SWORD		oUNSIGNED_ATTRIBUTE;
		SWORD		oMONEY;
		SWORD		oAUTO_INCREMENT;
		char		oLOCAL_TYPE_NAME[TYPE_LEN];
		SWORD		oMINIMUM_SCALE;
		SWORD		oMAXIMUM_SCALE;

		SQLLEN	oTYPE_NAMElen;	
		SQLLEN	oDATA_TYPElen;
		SQLLEN	oPRECISIONlen;
		SQLLEN	oLITERAL_PREFIXlen;
		SQLLEN	oLITERAL_SUFFIXlen;
		SQLLEN	oCREATE_PARAMSlen;
		SQLLEN	oNULLABLElen;
		SQLLEN	oCASE_SENSITIVElen;
		SQLLEN	oSEARCHABLElen;
		SQLLEN	oUNSIGNED_ATTRIBUTElen;
		SQLLEN	oMONEYlen;
		SQLLEN	oAUTO_INCREMENTlen;
		SQLLEN	oLOCAL_TYPE_NAMElen;
		SQLLEN	oMINIMUM_SCALElen;
		SQLLEN	oMAXIMUM_SCALElen;

   	/* Set up some local variables to save on typing in longer ones */
    /* This previously was R1.8 */
//================Modified for Longvarchar Changes===========================================================
if(!pTestInfo->bLongOn)
{
	char *TYPE_NAME = "VARCHAR";
	SWORD DATA_TYPE = SQL_VARCHAR;
    SDWORD	PRECISION = 32000;
	char *CREATE_PARAMS = "max length";
	char *LOCAL_TYPE_NAME = "VARCHAR";


	TypeInfo[1].PRECISION = PRECISION;
	TypeInfo[2].PRECISION = PRECISION;

	TypeInfo[14].TYPE_NAME = TYPE_NAME;
	TypeInfo[14].DATA_TYPE = DATA_TYPE;
	TypeInfo[14].PRECISION = PRECISION;
	TypeInfo[14].CREATE_PARAMS = CREATE_PARAMS;
	TypeInfo[14].LOCAL_TYPE_NAME = LOCAL_TYPE_NAME;
}

//================Modified for Longvarhcar Changes===========================================================

	LogMsg(LINEBEFORE+SHORTTIMESTAMP,"Begin testing API =>SQLGetTypeInfo30 | SQLGetTypeInfo3 | gettypeiR18.c\n");

	TEST_INIT;
	TESTCASE_BEGIN("Setup for SQLGetTypeInfo tests for ODBC 3.0\n");

	if(!FullConnectWithOptions(pTestInfo, CONNECT_ODBC_VERSION_3))
	{
		LogMsg(NONE,"Unable to connect\n");
		TEST_FAILED;
		TEST_RETURN;
	}

  	/* Set up some local variables to save on typing in longer ones */
	henv = pTestInfo->henv;
	hdbc = pTestInfo->hdbc;
 	hstmt = (SQLHANDLE)pTestInfo->hstmt;
   	
	returncode = SQLAllocHandle(SQL_HANDLE_STMT, (SQLHANDLE)hdbc, &hstmt);
	if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocHandle")){
		LogAllErrorsVer3(henv,hdbc,hstmt);
		TEST_FAILED;
		TEST_RETURN;
	}
	
	TESTCASE_END; // end of setup

//=========================================================================================
					 
/*	if (MX_MP_SPECIFIC == MX_SPECIFIC)
		END_LOOP = SQL_BINARY;
	else if (MX_MP_SPECIFIC == MP_SPECIFIC)
		END_LOOP = 999;
	else
	{
		LogMsg(ERRMSG,"gettypeinfo test failed.\n");
		TEST_RETURN;
	}
*/	
	END_LOOP = 999;
	j = 0;
	while (TypeInfo[j].DATA_TYPE != END_LOOP) 
	{
		sprintf(Heading,"Test Positive functionality of SQLGetTypeInfo for data type: %s\n",
									SQLTypeToChar(TypeInfo[j].DATA_TYPE,TempBuf));
		TESTCASE_BEGIN(Heading);

		returncode = SQLGetTypeInfo(hstmt,TypeInfo[j].DATA_TYPE);
		if(!CHECKRC(SQL_SUCCESS,returncode,"SQLGetTypeInfo"))
		{
			TEST_FAILED;
			LogAllErrors(henv,hdbc,hstmt);
		}
		else
		{
			if (TypeInfo[j].DATA_TYPE != 0) 
			{ 
				strcpy(oTYPE_NAME,"");
				oDATA_TYPE = 0; 
				oPRECISION = 0;
				strcpy(oLITERAL_PREFIX,"");
				strcpy(oLITERAL_SUFFIX,"");
				strcpy(oCREATE_PARAMS,"");
				oNULLABLE = 0;
				oCASE_SENSITIVE = 0;
				oSEARCHABLE = 0;
				oUNSIGNED_ATTRIBUTE = 0;
				oMONEY = 0;
				oAUTO_INCREMENT = 0;
				strcpy(oLOCAL_TYPE_NAME,"");
				oMINIMUM_SCALE = 0;
				oMAXIMUM_SCALE = 0;
				returncode = SQLBindCol(hstmt,1,SQL_C_CHAR,oTYPE_NAME,TYPE_LEN,&oTYPE_NAMElen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,2,SQL_C_SHORT,&oDATA_TYPE,0,&oDATA_TYPElen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,3,SQL_C_LONG,&oPRECISION,0,&oPRECISIONlen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,4,SQL_C_CHAR,oLITERAL_PREFIX,TYPE_LEN,&oLITERAL_PREFIXlen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,5,SQL_C_CHAR,oLITERAL_SUFFIX,TYPE_LEN,&oLITERAL_SUFFIXlen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,6,SQL_C_CHAR,oCREATE_PARAMS,TYPE_LEN,&oCREATE_PARAMSlen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,7,SQL_C_SHORT,&oNULLABLE,0,&oNULLABLElen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,8,SQL_C_SHORT,&oCASE_SENSITIVE,0,&oCASE_SENSITIVElen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,9,SQL_C_SHORT,&oSEARCHABLE,0,&oSEARCHABLElen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,10,SQL_C_SHORT,&oUNSIGNED_ATTRIBUTE,0,&oUNSIGNED_ATTRIBUTElen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,11,SQL_C_SHORT,&oMONEY,0,&oMONEYlen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,12,SQL_C_SHORT,&oAUTO_INCREMENT,0,&oAUTO_INCREMENTlen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,13,SQL_C_CHAR,oLOCAL_TYPE_NAME,TYPE_LEN,&oLOCAL_TYPE_NAMElen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,14,SQL_C_SHORT,&oMINIMUM_SCALE,0,&oMINIMUM_SCALElen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLBindCol(hstmt,15,SQL_C_SHORT,&oMAXIMUM_SCALE,0,&oMAXIMUM_SCALElen);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol"))
				{
						LogAllErrors(henv,hdbc,hstmt);
						TEST_FAILED;
				}
				returncode = SQLFetch(hstmt);
				if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFetch"))
				{
					TEST_FAILED;
					LogAllErrors(henv,hdbc,hstmt);
				}
				else
				{
					LogMsg(NONE,"Comparing results\n");
					if ((_stricmp(TypeInfo[j].TYPE_NAME,oTYPE_NAME) == 0)
							&& (TypeInfo[j].DATA_TYPE == oDATA_TYPE)
							&& (TypeInfo[j].PRECISION == oPRECISION)
							&& (_stricmp(TypeInfo[j].LITERAL_PREFIX,oLITERAL_PREFIX) == 0)
							&& (_stricmp(TypeInfo[j].LITERAL_SUFFIX,oLITERAL_SUFFIX) == 0)
							&& (_stricmp(TypeInfo[j].CREATE_PARAMS,oCREATE_PARAMS) == 0)
							&& (TypeInfo[j].NULLABLE == oNULLABLE)
							&& (TypeInfo[j].CASE_SENSITIVE == oCASE_SENSITIVE)
							&& (TypeInfo[j].SEARCHABLE == oSEARCHABLE)
							&& (TypeInfo[j].UNSIGNED_ATTRIBUTE == oUNSIGNED_ATTRIBUTE)
							&& (TypeInfo[j].MONEY == oMONEY)
							&& (TypeInfo[j].AUTO_INCREMENT == oAUTO_INCREMENT)
							&& (_stricmp(TypeInfo[j].LOCAL_TYPE_NAME,oLOCAL_TYPE_NAME) == 0)
							&& (TypeInfo[j].MINIMUM_SCALE == oMINIMUM_SCALE)
							&& (TypeInfo[j].MAXIMUM_SCALE == oMAXIMUM_SCALE))
					{
						//LogMsg(NONE,"Data Type Name actual: %s and expected: %s are matched\n",oTYPE_NAME,TypeInfo[j].TYPE_NAME);
						//LogMsg(NONE,"Data Type actual: %d and expected: %d are matched\n",oDATA_TYPE,TypeInfo[j].DATA_TYPE);
						//LogMsg(NONE,"Precision actual: %d and expected: %d are matched\n",oPRECISION,TypeInfo[j].PRECISION);
						//LogMsg(NONE,"Literal Prefix actual: %s and expected: %s are matched\n",oLITERAL_PREFIX,TypeInfo[j].LITERAL_PREFIX);
						//LogMsg(NONE,"Literal Suffix actual: %s and expected: %s are matched\n",oLITERAL_SUFFIX,TypeInfo[j].LITERAL_SUFFIX);
						//LogMsg(NONE,"Create Params actual: %s and expected: %s are matched\n",oCREATE_PARAMS,TypeInfo[j].CREATE_PARAMS);
						//LogMsg(NONE,"Nullable actual: %d and expected: %d are matched\n",oNULLABLE,TypeInfo[j].NULLABLE);
						//LogMsg(NONE,"Case sensitive actual: %d and expected: %d are matched\n",oCASE_SENSITIVE,TypeInfo[j].CASE_SENSITIVE);
						//LogMsg(NONE,"Searchable actual: %d and expected: %d are matched\n",oSEARCHABLE,TypeInfo[j].SEARCHABLE);
						//LogMsg(NONE,"Unsigned attribute actual: %d and expected: %d are matched\n",oUNSIGNED_ATTRIBUTE,TypeInfo[j].UNSIGNED_ATTRIBUTE);
						//LogMsg(NONE,"Money actual: %d and expected: %d are matched\n",oMONEY,TypeInfo[j].MONEY);
						//LogMsg(NONE,"Auto Increment actual: %d and expected: %d are matched\n",oAUTO_INCREMENT,TypeInfo[j].AUTO_INCREMENT);
						//LogMsg(NONE,"Local Type name actual: %s and expected: %s are matched\n",oLOCAL_TYPE_NAME,TypeInfo[j].LOCAL_TYPE_NAME);
						//LogMsg(NONE,"Minimum Scale actual: %d and expected: %d are matched\n",oMINIMUM_SCALE,TypeInfo[j].MINIMUM_SCALE);
						//LogMsg(NONE,"Maximum Scale actual: %d and expected: %d are matched\n",oMAXIMUM_SCALE,TypeInfo[j].MAXIMUM_SCALE);
					}	
					else
					{
						TEST_FAILED;	
						if (_stricmp(TypeInfo[j].TYPE_NAME,oTYPE_NAME) != 0)
							LogMsg(ERRMSG,"Data Type Name actual: %s and expected: %s are not matched\n",oTYPE_NAME,TypeInfo[j].TYPE_NAME);
						if (TypeInfo[j].DATA_TYPE != oDATA_TYPE)
							LogMsg(ERRMSG,"Data Type actual: %d and expected: %d are not matched\n",oDATA_TYPE,TypeInfo[j].DATA_TYPE);
						if (TypeInfo[j].PRECISION != oPRECISION)
							LogMsg(ERRMSG,"Precision actual: %d and expected: %d are not matched\n",oPRECISION,TypeInfo[j].PRECISION);
						if (_stricmp(TypeInfo[j].LITERAL_PREFIX,oLITERAL_PREFIX) != 0)
							LogMsg(ERRMSG,"Literal Prefix actual: %s and expected: %s are not matched\n",oLITERAL_PREFIX,TypeInfo[j].LITERAL_PREFIX);
						if (_stricmp(TypeInfo[j].LITERAL_SUFFIX,oLITERAL_SUFFIX) != 0)
							LogMsg(ERRMSG,"Literal Suffix actual: %s and expected: %s are not matched\n",oLITERAL_SUFFIX,TypeInfo[j].LITERAL_SUFFIX);
						if (_stricmp(TypeInfo[j].CREATE_PARAMS,oCREATE_PARAMS) != 0)
							LogMsg(ERRMSG,"Create Params actual: %s and expected: %s are not matched\n",oCREATE_PARAMS,TypeInfo[j].CREATE_PARAMS);
						if (TypeInfo[j].NULLABLE != oNULLABLE)
							LogMsg(ERRMSG,"Nullable actual: %d and expected: %d are not matched\n",oNULLABLE,TypeInfo[j].NULLABLE);
						if (TypeInfo[j].CASE_SENSITIVE != oCASE_SENSITIVE)
							LogMsg(ERRMSG,"Case sensitive actual: %d and expected: %d are not matched\n",oCASE_SENSITIVE,TypeInfo[j].CASE_SENSITIVE);
						if (TypeInfo[j].SEARCHABLE != oSEARCHABLE)
							LogMsg(ERRMSG,"Searchable actual: %d and expected: %d are not matched\n",oSEARCHABLE,TypeInfo[j].SEARCHABLE);
						if (TypeInfo[j].UNSIGNED_ATTRIBUTE != oUNSIGNED_ATTRIBUTE)
							LogMsg(ERRMSG,"Unsigned attribute actual: %d and expected: %d are not matched\n",oUNSIGNED_ATTRIBUTE,TypeInfo[j].UNSIGNED_ATTRIBUTE);
						if (TypeInfo[j].MONEY != oMONEY)
							LogMsg(ERRMSG,"Money actual: %d and expected: %d are not matched\n",oMONEY,TypeInfo[j].MONEY);
						if (TypeInfo[j].AUTO_INCREMENT != oAUTO_INCREMENT)
							LogMsg(ERRMSG,"Auto Increment actual: %d and expected: %d are not matched\n",oAUTO_INCREMENT,TypeInfo[j].AUTO_INCREMENT);
						if (_stricmp(TypeInfo[j].LOCAL_TYPE_NAME,oLOCAL_TYPE_NAME) != 0)
							LogMsg(ERRMSG,"Local Type name actual: %s and expected: %s are not matched\n",oLOCAL_TYPE_NAME,TypeInfo[j].LOCAL_TYPE_NAME);
						if (TypeInfo[j].MINIMUM_SCALE != oMINIMUM_SCALE)
							LogMsg(ERRMSG,"Minimum Scale actual: %d and expected: %d are not matched\n",oMINIMUM_SCALE,TypeInfo[j].MINIMUM_SCALE);
						if (TypeInfo[j].MAXIMUM_SCALE != oMAXIMUM_SCALE)
							LogMsg(ERRMSG,"Maximum Scale actual: %d and expected: %d are not matched\n",oMAXIMUM_SCALE,TypeInfo[j].MAXIMUM_SCALE);
					}
				} 					
			}
		}
		TESTCASE_END;
		SQLFreeStmt(hstmt,SQL_CLOSE);	// This is a bug this should be after the inner for loop.
		j++;
	} 															
	
//==========================================================================================
	
	TESTCASE_BEGIN("SQLGetTypeInfo: Negative test for invalid data type\n");

	fSqlType1 = 50;
	returncode = SQLGetTypeInfo(hstmt,fSqlType1);
	if(!CHECKRC(SQL_ERROR,returncode,"SQLGetTypeInfo"))
	{
		TEST_FAILED;
		LogAllErrors(henv,hdbc,hstmt);
	}
	TESTCASE_END;

//=========================================================================================

	sprintf(Heading,"SQLGetTypeInfo: Negative test with invalid handle\n");
	TESTCASE_BEGIN(Heading);

	hstmt = (SQLHANDLE)NULL;
	fSqlType1 = 1;
	returncode = SQLGetTypeInfo(hstmt,fSqlType1);
	if(!CHECKRC(SQL_INVALID_HANDLE,returncode,"SQLGetTypeInfo"))
	{
		TEST_FAILED;
		LogAllErrors(henv,hdbc,hstmt);
	}
	TESTCASE_END;

//=========================================================================================

	FullDisconnect3(pTestInfo);
	LogMsg(SHORTTIMESTAMP+LINEAFTER,"End testing API => SQLGetTypeInfo.\n");
	TEST_RETURN;
}
Esempio n. 14
0
int main(int argc, char **argv)
{
	SQLRETURN rc;
	HSTMT hstmt = SQL_NULL_HSTMT;
	char *param1;
	SQLLEN cbParam1;
	SQLINTEGER longparam;
	SQL_INTERVAL_STRUCT intervalparam;
	SQLSMALLINT colcount;
	char		byteaParam[5000];
	int			i;

	test_connect();

	rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
	if (!SQL_SUCCEEDED(rc))
	{
		print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
		exit(1);
	}

	/**** A simple query with one text param ****/

	rc = SQLExecDirect(hstmt, (SQLCHAR *) "SET intervalstyle=postgres_verbose", SQL_NTS);
	/* Prepare a statement */
	rc = SQLPrepare(hstmt, (SQLCHAR *) "SELECT id, t FROM testtab1 WHERE t = ?", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);

	/* bind param  */
	param1 = "bar";
	cbParam1 = SQL_NTS;
	rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
						  SQL_C_CHAR,	/* value type */
						  SQL_CHAR,		/* param type */
						  20,			/* column size */
						  0,			/* dec digits */
						  param1,		/* param value ptr */
						  0,			/* buffer len */
						  &cbParam1		/* StrLen_or_IndPtr */);
	CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);

	/* Test SQLNumResultCols, called before SQLExecute() */
	rc = SQLNumResultCols(hstmt, &colcount);
	CHECK_STMT_RESULT(rc, "SQLNumResultCols failed", hstmt);
	printf("# of result cols: %d\n", colcount);

	/* Execute */
	rc = SQLExecute(hstmt);
	CHECK_STMT_RESULT(rc, "SQLExecute failed", hstmt);

	/* Fetch result */
	print_result(hstmt);

	rc = SQLFreeStmt(hstmt, SQL_CLOSE);
	CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);

	/**** A query with an integer param ****/

	/* Prepare a statement */
	rc = SQLPrepare(hstmt, (SQLCHAR *) "SELECT id, t FROM testtab1 WHERE id = ?", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);

	/* bind param  */
	longparam = 3;
	cbParam1 = sizeof(longparam);
	rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
						  SQL_C_SLONG,	/* value type */
						  SQL_INTEGER,	/* param type */
						  0,			/* column size (ignored for SQL_INTEGER) */
						  0,			/* dec digits */
						  &longparam,	/* param value ptr */
						  sizeof(longparam), /* buffer len (ignored for SQL_INTEGER) */
						  &cbParam1		/* StrLen_or_IndPtr (ignored for SQL_INTEGER) */);
	CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);

	/* Execute */
	rc = SQLExecute(hstmt);
	CHECK_STMT_RESULT(rc, "SQLExecute failed", hstmt);

	/* Fetch result */
	print_result(hstmt);

	rc = SQLFreeStmt(hstmt, SQL_CLOSE);
	CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);

	/**** Test a query with a bytea param of various sizes.  ****/

	/*
	 * The driver has some special handling for byteas, as it sends them in
	 * binary mode. This particular test case exercises an old bug where
	 * the bind packet size was calculated incorrectly, and there was an
	 * out-of-bounds write of two bytes when the total packet size was exactly
	 * 4097 bytes. So, exercise packet sizes near that boundary.
	 */

	rc = SQLExecDirect(hstmt,
					   (SQLCHAR *) "CREATE TEMPORARY TABLE btest (len int4, b bytea)",
					   SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);

	/* Prepare a statement */
	rc = SQLPrepare(hstmt, (SQLCHAR *) "INSERT INTO btest VALUES(?, ?)", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);

	/* fill in test data */
	for (i = 0; i < sizeof(byteaParam); i++)
		byteaParam[i] = (char) i;

	printf ("inserting bytea values...");
	for (i = 4000; i < 4100; i++)
	{
		printf(" %d", i); fflush(stdout);
		/* bind int param  */
		longparam = i;
		cbParam1 = sizeof(longparam);
		rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
							  SQL_C_SLONG,	/* value type */
							  SQL_INTEGER,	/* param type */
							  0,			/* column size (ignored for SQL_INTEGER) */
							  0,			/* dec digits */
							  &longparam,	/* param value ptr */
							  sizeof(longparam), /* buffer len (ignored for SQL_INTEGER) */
							  &cbParam1		/* StrLen_or_IndPtr (ignored for SQL_INTEGER) */);
		CHECK_STMT_RESULT(rc, "\nSQLBindParameter failed", hstmt);

		cbParam1 = i;
		rc = SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT,
							  SQL_C_BINARY,	/* value type */
							  SQL_VARBINARY,	/* param type */
							  sizeof(byteaParam), /* column size */
							  0,			/* dec digits */
							  byteaParam,	/* param value ptr */
							  sizeof(byteaParam), /* buffer len */
							  &cbParam1		/* StrLen_or_IndPtr */);
		CHECK_STMT_RESULT(rc, "\nSQLBindParameter failed", hstmt);

		/* Execute */
		rc = SQLExecute(hstmt);
		CHECK_STMT_RESULT(rc, "\nSQLExecute failed", hstmt);
	}
	printf(" done!\n");
	printf("Now reading them back...\n");

	rc = SQLFreeStmt(hstmt, SQL_CLOSE);
	CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);

	/* Check the inserted data */
	rc = SQLExecDirect(hstmt,
					   (SQLCHAR *) "SELECT len, length(b) FROM btest",
					   SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
	print_result(hstmt);

	rc = SQLFreeStmt(hstmt, SQL_CLOSE);
	CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);

	/**** A query with an interval param (SQL_C_INTERVAL_SECOND) ****/

	/* Prepare a statement */
	rc = SQLPrepare(hstmt, (SQLCHAR *) "SELECT id, iv, d FROM intervaltable WHERE iv < ?", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);

	/* bind param  */
	intervalparam.interval_type = SQL_IS_SECOND;
	intervalparam.interval_sign = 0;
	intervalparam.intval.day_second.day = 1;
	intervalparam.intval.day_second.hour = 2;
	intervalparam.intval.day_second.minute = 3;
	intervalparam.intval.day_second.second = 4;
	intervalparam.intval.day_second.fraction = 5;

	cbParam1 = sizeof(intervalparam);
	rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
						  SQL_C_INTERVAL_SECOND,	/* value type */
						  SQL_INTERVAL_SECOND,	/* param type */
						  0,			/* column size (ignored for SQL_INTERVAL_SECOND) */
						  0,			/* dec digits */
						  &intervalparam, /* param value ptr */
						  sizeof(intervalparam), /* buffer len (ignored for SQL_C_INTERVAL_SECOND) */
						  &cbParam1 /* StrLen_or_IndPtr (ignored for SQL_C_INTERVAL_SECOND) */);
	CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);

	/* Execute */
	rc = SQLExecute(hstmt);
	CHECK_STMT_RESULT(rc, "SQLExecute failed", hstmt);

	/* Fetch result */
	print_result(hstmt);

	rc = SQLFreeStmt(hstmt, SQL_CLOSE);
	CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);


	/****
	 * With BoolsAsChar=1, a varchar param with column_size=5 forces a
	 * server-side Prepare. So test that.
	 */

	/* Prepare a statement */
	rc = SQLPrepare(hstmt, (SQLCHAR *) "SELECT id, t FROM testtab1 WHERE id = ?", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);

	/* bind param  */
	param1 = "2";
	cbParam1 = SQL_NTS;
	rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
						  SQL_C_CHAR,	/* value type */
						  SQL_VARCHAR,	/* param type */
						  5,			/* column size. 5 Triggers special
										 * behavior with BoolsAsChar=1 */
						  0,			/* dec digits */
						  param1,		/* param value ptr */
						  0,			/* buffer len */
						  &cbParam1		/* StrLen_or_IndPtr */);
	CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);

	/* Test SQLNumResultCols, called before SQLExecute() */
	rc = SQLNumResultCols(hstmt, &colcount);
	CHECK_STMT_RESULT(rc, "SQLNumResultCols failed", hstmt);
	printf("# of result cols: %d\n", colcount);

	/* Execute */
	rc = SQLExecute(hstmt);
	CHECK_STMT_RESULT(rc, "SQLExecute failed", hstmt);

	/* Fetch result */
	print_result(hstmt);

	rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
	if (!SQL_SUCCEEDED(rc))
	{
		print_diag("SQLFreeStmt failed", SQL_HANDLE_STMT, hstmt);
		exit(1);
	}

	/* Clean up */
	test_disconnect();

	return 0;
}
Esempio n. 15
0
int main(int argc, char **argv)
{
	int			rc;
	HSTMT		hstmt = SQL_NULL_HSTMT;
	/*
	 * NOTE: in the psqlodbc, we assume that SQL_C_LONG actually means a
	 * variable of type SQLINTEGER. They are not the same on platforms where
	 * "long" is a 64-bit integer. That seems a bit bogus, but it's too late
	 * to change that without breaking applications that depend on it.
	 * (on little-endian systems, you won't notice the difference if you reset
	 * the high bits to zero before calling SQLBindCol.)
	 */
	SQLINTEGER	longvalue;
	SQLLEN		indLongvalue;
	char		charvalue[100];
	SQLLEN		indCharvalue;
	int			rowno;

	test_connect();

	rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
	if (!SQL_SUCCEEDED(rc))
	{
		print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
		exit(1);
	}

	rc = SQLBindCol(hstmt, 1, SQL_C_LONG, &longvalue, 0, &indLongvalue);
	CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);

	rc = SQLBindCol(hstmt, 2, SQL_C_CHAR, &charvalue, sizeof(charvalue), &indCharvalue);
	CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);

	rc = SQLExecDirect(hstmt, (SQLCHAR *)
					   "SELECT id, 'foo' || id FROM generate_series(1, 10) id", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);

	printf("Result set:\n");
	rowno = 0;
	while(1)
	{
		rc = SQLFetch(hstmt);
		if (rc == SQL_NO_DATA)
			break;
		if (rc == SQL_SUCCESS)
		{
			printf("%ld %s\n", (long) longvalue, charvalue);
		}
		else
		{
			print_diag("SQLFetch failed", SQL_HANDLE_STMT, hstmt);
			exit(1);
		}

		/*
		 * At row 3, unbind the text field. At row 5, bind it again.
		 * At row 7, unbind both columns with SQLFreeStmt(SQL_UNBIND).
		 * At row 9, bind text field again.
		 */
		rowno++;
		if (rowno == 3)
		{
			rc = SQLBindCol(hstmt, 2, SQL_C_CHAR, NULL, 0, NULL);
			CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
		}
		if (rowno == 7)
		{
			rc = SQLFreeStmt(hstmt, SQL_UNBIND);
			CHECK_STMT_RESULT(rc, "SQLFreeStmt(SQL_UNBIND) failed", hstmt);
		}
		if (rowno == 5 || rowno == 9)
		{
			rc = SQLBindCol(hstmt, 2, SQL_C_CHAR, &charvalue, sizeof(charvalue), &indCharvalue);
			CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);
		}
	}

	rc = SQLFreeStmt(hstmt, SQL_CLOSE);
	CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);

	/* Clean up */
	test_disconnect();

	return 0;
}
Esempio n. 16
0
// Main Program
int main (int argc, char **argv)
{
	SQLCHAR		*dsnName;
	SQLCHAR		*user;
	SQLCHAR		*password;
	SQLRETURN	returnCode;
	bool		testPassed = true;
	SQLCHAR		InConnStr[MAX_CONNECT_STRING];
	SQLCHAR		OutConnStr[MAX_CONNECT_STRING];
	SQLSMALLINT	ConnStrLength;
	int c, errflag = 0;
	
	optarg = NULL;
	if (argc != 7)
		errflag++;

	while (!errflag && (c = getopt(argc, argv, ARGS)) != -1)
		switch (c) {
			case 'd':
				dsnName = (SQLCHAR*)optarg;	
				break;
			case 'u':
				user = (SQLCHAR*)optarg;
				break;
			case 'p':
				password = (SQLCHAR*)optarg;
				break;
			default :
				errflag++;
		}
	if (errflag) {
		printf("Command line error.\n");
		printf("Usage: %s [-d <datasource>] [-u <userid>] [-p <password>]\n", argv[0] );
		return FALSE;
	}

	// Initialize handles to NULL
	henv = SQL_NULL_HANDLE;
	hstmt = SQL_NULL_HANDLE;
	hdbc = SQL_NULL_HANDLE;

	// Allocate Environment Handle
	returnCode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv)",returnCode);

	// Set ODBC version to 3.0
	returnCode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0)",returnCode,false);

	// Allocate Connection handle
	returnCode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc)", returnCode);

	//Connect to the database
	sprintf((char*)InConnStr,"DSN=%s;UID=%s;PWD=%s;%c",(char*)dsnName, (char*)user, (char*)password,'\0');
	printf("Using Connect String: %s\n", InConnStr);
	returnCode = SQLDriverConnect(hdbc,hWnd,InConnStr,SQL_NTS,OutConnStr,sizeof(OutConnStr),&ConnStrLength,SQL_DRIVER_NOPROMPT);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLDriverConnect",returnCode);

	//Allocate Statement handle
	returnCode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt)", returnCode);

	//Free Statement handle
	returnCode = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLFreeHandle(SQL_HANDLE_STMT, hstmt)", returnCode);
	hstmt = SQL_NULL_HANDLE;

	//Disconnect
	returnCode = SQLDisconnect(hdbc);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLDisconnect(hdbc)", returnCode);

	//Free Connection handle
	returnCode = SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLFreeHandle(SQL_HANDLE_DBC, hdbc)", returnCode);
	hdbc = SQL_NULL_HANDLE;

	//Free Environment handle
	returnCode = SQLFreeHandle(SQL_HANDLE_ENV, henv);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLFreeHandle(SQL_HANDLE_ENV, henv)", returnCode);
	henv = SQL_NULL_HANDLE;

	printf("\nConnect Test Passed...\n");
	exit(EXIT_SUCCESS);
}
Esempio n. 17
0
int main(int argc, char **argv)
{
  SQLHENV     hEnv = NULL;
  SQLHDBC     hDbc = NULL;
  SQLHSTMT    hStmt = NULL;
  char*       pConnStr;
  char        pQuery[1000];
  bool        silent = true;

  if (argc != 5) {
    fprintf(stderr, "Usage: %s <ConnString> <pkey range> <ccol range> <rand seed>\n", argv[0]);
    return 1;
  }
  pConnStr = argv[1];
  char *endptr;
  long long numkeys = strtoll(argv[2], &endptr, 10);
  long long rowsperkey = strtoll(argv[3], &endptr, 10);
  int seed = atoi(argv[4]);
  struct drand48_data lcg;
  srand48_r(seed, &lcg);

  // Allocate an environment
  if (!silent)
    fprintf(stderr, "Allocating Handle Enviroment\n");
  if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv) == SQL_ERROR)
    {
      fprintf(stderr, "Unable to allocate an environment handle\n");
      exit(-1);
    }

  // Register this as an application that expects 3.x behavior,
  // you must register something if you use AllocHandle
  if (!silent)
    fprintf(stderr, "Setting to ODBC3\n");
  TRYODBC(hEnv,
	  SQL_HANDLE_ENV,
	  SQLSetEnvAttr(hEnv,
			SQL_ATTR_ODBC_VERSION,
			(SQLPOINTER)SQL_OV_ODBC3,
			0));

  // Allocate a connection
  if (!silent)
    fprintf(stderr, "Allocating Handle\n");
  TRYODBC(hEnv,
	  SQL_HANDLE_ENV,
	  SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc));

  // Connect to the driver.  Use the connection string if supplied
  // on the input, otherwise let the driver manager prompt for input.
  if (!silent)
    fprintf(stderr, "Connecting to driver\n");
  TRYODBC(hDbc,
	  SQL_HANDLE_DBC,
	  SQLDriverConnect(hDbc,
			   NULL,
			   pConnStr,
			   SQL_NTS,
			   NULL,
			   0,
			   NULL,
			   SQL_DRIVER_COMPLETE));

  fprintf(stderr, "Connected!\n");

  if (!silent)
    fprintf(stderr, "Allocating statement\n");
  TRYODBC(hDbc,
	  SQL_HANDLE_DBC,
	  SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt));

  RETCODE     RetCode;
  SQLSMALLINT sNumResults;

  // Execute the query
  if (!silent)
    fprintf(stderr, "Executing query\n");
  long long i;
  double rval;
  for (i = 0; i < 100000; i++) {
    drand48_r(&lcg, &rval);
    sprintf(pQuery, "SELECT MAX(col1) FROM otest.test10 WHERE ccol = %lld", (long long)(rval * numkeys));
    RetCode = SQLExecDirect(hStmt, pQuery, SQL_NTS);

    switch(RetCode)
      {
      case SQL_SUCCESS_WITH_INFO:
	{
	  HandleDiagnosticRecord(hStmt, SQL_HANDLE_STMT, RetCode);
	  // fall through
	}
      case SQL_SUCCESS:
	{
	  // If this is a row-returning query, display
	  // results
	  TRYODBC(hStmt,
		  SQL_HANDLE_STMT,
		  SQLNumResultCols(hStmt,&sNumResults));
	  
	  if (sNumResults > 0)
	    {
	      DisplayResults(hStmt,sNumResults, silent);
	    } 
	  else
	    {
	      SQLLEN cRowCount;
	      
	      TRYODBC(hStmt,
		      SQL_HANDLE_STMT,
		      SQLRowCount(hStmt,&cRowCount));
	      
	      if (cRowCount >= 0)
		{
		  printf("%d %s returned\n",
			 (int)cRowCount,
			 (cRowCount == 1) ? "row" : "rows");
		}
	    }
	  break;
	}
	
      case SQL_ERROR:
	{
	  HandleDiagnosticRecord(hStmt, SQL_HANDLE_STMT, RetCode);
	  break;
	}
	
      default:
	fprintf(stderr, "Unexpected return code %hd!\n", RetCode);
	
      }
  }

  TRYODBC(hStmt,
	  SQL_HANDLE_STMT,
	  SQLFreeStmt(hStmt, SQL_CLOSE));

 Exit:

  // Free ODBC handles and exit

  if (hStmt)
    {
      SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
    }

  if (hDbc)
    {
      SQLDisconnect(hDbc);
      SQLFreeHandle(SQL_HANDLE_DBC, hDbc);
    }

  if (hEnv)
    {
      SQLFreeHandle(SQL_HANDLE_ENV, hEnv);
    }

  return 0;

}
Esempio n. 18
0
int	odbc_DBconnect(ZBX_ODBC_DBH *pdbh, const char *db_dsn, const char *user, const char *pass)
{
	SQLCHAR
		err_stat[10],
		err_msg[100];

	SQLINTEGER
		err_int;

	SQLSMALLINT
		err_msg_len;

	SQLRETURN	retcode;

	clean_odbc_strerror();

	memset(pdbh, 0 , sizeof(ZBX_ODBC_DBH));

	zabbix_log(LOG_LEVEL_DEBUG, "ODBC connect [%s] [%s]", db_dsn, user);

	/*Allocate environment handle */
	retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &(pdbh->henv));
	if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
	{
		set_last_odbc_strerror("%s","failed environment handle allocation.");
	}
	else
	{
		/* Set the ODBC version environment attribute */
		retcode = SQLSetEnvAttr(pdbh->henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
		if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
		{
			set_last_odbc_strerror("%s","failed ODBC version setting.");
		}
		else
		{
			/* Allocate connection handle */
			retcode = SQLAllocHandle(SQL_HANDLE_DBC, pdbh->henv, &(pdbh->hdbc));
			if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
			{
				set_last_odbc_strerror("%s","failed connection handle allocation.");
			}
			else
			{
				/* Set login timeout to 5 seconds. */
				SQLSetConnectAttr(pdbh->hdbc, (SQLINTEGER)SQL_LOGIN_TIMEOUT, (SQLPOINTER)5, (SQLINTEGER)0);

				/* Connect to data source */
				retcode = SQLConnect(pdbh->hdbc,
					(SQLCHAR*) db_dsn, SQL_NTS,
					(SQLCHAR*) user, SQL_NTS,
					(SQLCHAR*) pass, SQL_NTS
					);
				if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
				{

					SQLGetDiagRec(SQL_HANDLE_DBC,
							pdbh->hdbc,
							1,
							err_stat,
							&err_int,
							err_msg,
							sizeof(err_msg),
							&err_msg_len
							);

					set_last_odbc_strerror("failed connection [%s] (%d)", err_msg, err_int);
				}
				else
				{
					pdbh->connected = 1;

					/* Allocate statement handle */
					retcode = SQLAllocHandle(SQL_HANDLE_STMT, pdbh->hdbc, &(pdbh->hstmt));

					if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
					{
						return SUCCEED;
					}
					else
					{
						SQLFreeHandle(SQL_HANDLE_STMT, pdbh->hstmt);
						pdbh->hstmt = NULL;
					}
					SQLDisconnect(pdbh->hdbc);
				}
				SQLFreeHandle(SQL_HANDLE_DBC, pdbh->hdbc);
				pdbh->hdbc = NULL;
			}
		}
		SQLFreeHandle(SQL_HANDLE_ENV, pdbh->henv);
		pdbh->henv = NULL;
	}

	zabbix_log(LOG_LEVEL_ERR, "Failed to connect to DSN '%s' : Error: %s", db_dsn, get_last_odbc_strerror());
	return FAIL; /* error */
}
Esempio n. 19
0
static int odbc_log(struct ast_cdr *cdr)
{
	int ODBC_res;
	char sqlcmd[2048] = "", timestr[128];
	int res = 0;
	struct tm tm;

	if (usegmtime) 
		gmtime_r(&cdr->start.tv_sec,&tm);
	else
		ast_localtime(&cdr->start.tv_sec, &tm, NULL);

	ast_mutex_lock(&odbc_lock);
	strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
	memset(sqlcmd,0,2048);
	if (loguniqueid) {
		snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s "
		"(calldate,clid,src,dst,dcontext,channel,dstchannel,lastapp,"
		"lastdata,duration,billsec,disposition,amaflags,accountcode,uniqueid,userfield) "
		"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", table);
	} else {
		snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s "
		"(calldate,clid,src,dst,dcontext,channel,dstchannel,lastapp,lastdata,"
		"duration,billsec,disposition,amaflags,accountcode) "
		"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", table);
	}

	if (!connected) {
		res = odbc_init();
		if (res < 0) {
			odbc_disconnect();
			ast_mutex_unlock(&odbc_lock);
			return 0;
		}				
	}

	ODBC_res = SQLAllocHandle(SQL_HANDLE_STMT, ODBC_con, &ODBC_stmt);

	if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) {
		if (option_verbose > 10)
			ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Failure in AllocStatement %d\n", ODBC_res);
		SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt);
		odbc_disconnect();
		ast_mutex_unlock(&odbc_lock);
		return 0;
	}

	/* We really should only have to do this once.  But for some
	   strange reason if I don't it blows holes in memory like
	   like a shotgun.  So we just do this so its safe. */

	ODBC_res = SQLPrepare(ODBC_stmt, (unsigned char *)sqlcmd, SQL_NTS);
	
	if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) {
		if (option_verbose > 10)
			ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Error in PREPARE %d\n", ODBC_res);
		SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt);
		odbc_disconnect();
		ast_mutex_unlock(&odbc_lock);
		return 0;
	}

	SQLBindParameter(ODBC_stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(timestr), 0, &timestr, 0, NULL);
	SQLBindParameter(ODBC_stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->clid), 0, cdr->clid, 0, NULL);
	SQLBindParameter(ODBC_stmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->src), 0, cdr->src, 0, NULL);
	SQLBindParameter(ODBC_stmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->dst), 0, cdr->dst, 0, NULL);
	SQLBindParameter(ODBC_stmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->dcontext), 0, cdr->dcontext, 0, NULL);
	SQLBindParameter(ODBC_stmt, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->channel), 0, cdr->channel, 0, NULL);
	SQLBindParameter(ODBC_stmt, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->dstchannel), 0, cdr->dstchannel, 0, NULL);
	SQLBindParameter(ODBC_stmt, 8, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->lastapp), 0, cdr->lastapp, 0, NULL);
	SQLBindParameter(ODBC_stmt, 9, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->lastdata), 0, cdr->lastdata, 0, NULL);
	SQLBindParameter(ODBC_stmt, 10, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->duration, 0, NULL);
	SQLBindParameter(ODBC_stmt, 11, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->billsec, 0, NULL);
	if (dispositionstring)
		SQLBindParameter(ODBC_stmt, 12, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(ast_cdr_disp2str(cdr->disposition)) + 1, 0, ast_cdr_disp2str(cdr->disposition), 0, NULL);
	else
		SQLBindParameter(ODBC_stmt, 12, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->disposition, 0, NULL);
	SQLBindParameter(ODBC_stmt, 13, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->amaflags, 0, NULL);
	SQLBindParameter(ODBC_stmt, 14, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->accountcode), 0, cdr->accountcode, 0, NULL);

	if (loguniqueid) {
		SQLBindParameter(ODBC_stmt, 15, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->uniqueid), 0, cdr->uniqueid, 0, NULL);
		SQLBindParameter(ODBC_stmt, 16, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->userfield), 0, cdr->userfield, 0, NULL);
	}

	if (connected) {
		res = odbc_do_query();
		if (res < 0) {
			if (option_verbose > 10)		
				ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Query FAILED Call not logged!\n");
			if (option_verbose > 10)
				ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Reconnecting to dsn %s\n", dsn);
			SQLDisconnect(ODBC_con);
			res = odbc_init();
			if (res < 0) {
				if (option_verbose > 10)
					ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: %s has gone away!\n", dsn);
				odbc_disconnect();
			} else {
				if (option_verbose > 10)
					ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Trying Query again!\n");
				res = odbc_do_query();
				if (res < 0) {
					if (option_verbose > 10)
						ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Query FAILED Call not logged!\n");
				}
			}
		}
	} else {
		if (option_verbose > 10)
			ast_verbose( VERBOSE_PREFIX_4 "cdr_odbc: Query FAILED Call not logged!\n");
	}
	SQLFreeHandle(SQL_HANDLE_STMT, ODBC_stmt);
	ast_mutex_unlock(&odbc_lock);
	return 0;
}
Esempio n. 20
0
static int db_is_up(switch_odbc_handle_t *handle)
{
	int ret = 0;
	SQLHSTMT stmt = NULL;
	SQLLEN m = 0;
	int result;
	switch_event_t *event;
	switch_odbc_status_t recon = 0;
	char *err_str = NULL;
	SQLCHAR sql[255] = "";
	int max_tries = 120;
	int code = 0;
	SQLRETURN rc;
	SQLSMALLINT nresultcols;


  top:

	if (!handle) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "No DB Handle\n");
		goto done;
	}

	if (handle->is_firebird) {
		strcpy((char *) sql, "select first 1 * from RDB$RELATIONS");
	} else {
		strcpy((char *) sql, "select 1");
	}

	if (SQLAllocHandle(SQL_HANDLE_STMT, handle->con, &stmt) != SQL_SUCCESS) {
		code = __LINE__;
		goto error;
	}

	if (SQLPrepare(stmt, sql, SQL_NTS) != SQL_SUCCESS) {
		code = __LINE__;
		goto error;
	}

	result = SQLExecute(stmt);

	if (result != SQL_SUCCESS && result != SQL_SUCCESS_WITH_INFO) {
		code = __LINE__;
		goto error;
	}

	SQLRowCount(stmt, &m);
	rc = SQLNumResultCols(stmt, &nresultcols);
	if (rc != SQL_SUCCESS) {
		code = __LINE__;
		goto error;
	}
	ret = (int) nresultcols;
	/* determine statement type */
	if (nresultcols <= 0) {
		/* statement is not a select statement */
		code = __LINE__;
		goto error;
	}

	goto done;

  error:
	err_str = switch_odbc_handle_get_error(handle, stmt);
	recon = switch_odbc_handle_connect(handle);

	max_tries--;

	if (switch_event_create(&event, SWITCH_EVENT_TRAP) == SWITCH_STATUS_SUCCESS) {
		switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Failure-Message", "The sql server is not responding for DSN %s [%s][%d]",
								switch_str_nil(handle->dsn), switch_str_nil(err_str), code);
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "The sql server is not responding for DSN %s [%s][%d]\n",
						  switch_str_nil(handle->dsn), switch_str_nil(err_str), code);

		if (recon == SWITCH_ODBC_SUCCESS) {
			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Additional-Info", "The connection has been re-established");
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "The connection has been re-established\n");
		} else {
			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Additional-Info", "The connection could not be re-established");
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "The connection could not be re-established\n");
		}
		if (!max_tries) {
			switch_event_add_header(event, SWITCH_STACK_BOTTOM, "Additional-Info", "Giving up!");
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Giving up!\n");
		}

		switch_event_fire(&event);
	}

	if (!max_tries) {
		goto done;
	}

	switch_safe_free(err_str);
	switch_yield(1000000);
	goto top;

  done:

	switch_safe_free(err_str);

	if (stmt) {
		SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	}

	return ret;
}
Esempio n. 21
0
int	odbc_DBconnect(ZBX_ODBC_DBH *pdbh, char *db_dsn, char *user, char *pass, int login_timeout)
{
	const char	*__function_name = "odbc_DBconnect";
	int		ret = FAIL;
	SQLRETURN	rc;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s() db_dsn:'%s' user:'******'", __function_name, db_dsn, user);

	clean_odbc_strerror();

	memset(pdbh, 0, sizeof(ZBX_ODBC_DBH));

	/* allocate environment handle */
	if (0 == SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &(pdbh->henv))))
	{
		set_last_odbc_strerror("%s", "Cannot create ODBC environment handle.");
		goto end;
	}

	/* set the ODBC version environment attribute */
	if (0 != CALLODBC(SQLSetEnvAttr(pdbh->henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0), rc, SQL_HANDLE_ENV,
			pdbh->henv, "Cannot set ODBC version"))
	{
		goto end;
	}

	/* allocate connection handle */
	if (0 != CALLODBC(SQLAllocHandle(SQL_HANDLE_DBC, pdbh->henv, &(pdbh->hdbc)), rc, SQL_HANDLE_ENV, pdbh->henv,
			"Cannot create ODBC connection handle"))
	{
		goto end;
	}

	/* set login timeout */
	if (0 != CALLODBC(SQLSetConnectAttr(pdbh->hdbc, (SQLINTEGER)SQL_LOGIN_TIMEOUT,
			(SQLPOINTER)(intptr_t)login_timeout, (SQLINTEGER)0), rc, SQL_HANDLE_DBC, pdbh->hdbc,
			"Cannot set ODBC login timeout"))
	{
		goto end;
	}

	/* connect to data source */
	if (0 != CALLODBC(SQLConnect(pdbh->hdbc, (SQLCHAR *)db_dsn, SQL_NTS, (SQLCHAR *)user, SQL_NTS, (SQLCHAR *)pass,
			SQL_NTS), rc, SQL_HANDLE_DBC, pdbh->hdbc, "Cannot connect to ODBC DSN"))
	{
		goto end;
	}

	/* allocate statement handle */
	if (0 != CALLODBC(SQLAllocHandle(SQL_HANDLE_STMT, pdbh->hdbc, &(pdbh->hstmt)), rc, SQL_HANDLE_DBC, pdbh->hdbc,
			"Cannot create ODBC statement handle."))
	{
		goto end;
	}

	pdbh->connected = 1;

	ret = SUCCEED;
end:
	if (SUCCEED != ret)
		odbc_DBclose(pdbh);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
Esempio n. 22
0
SWITCH_DECLARE(switch_odbc_status_t) switch_odbc_handle_connect(switch_odbc_handle_t *handle)
{
#ifdef SWITCH_HAVE_ODBC
	int result;
	SQLINTEGER err;
	int16_t mlen;
	unsigned char msg[200], stat[10];
	SQLSMALLINT valueLength = 0;
	int i = 0;

	if (handle->env == SQL_NULL_HANDLE) {
		result = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &handle->env);

		if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error AllocHandle\n");
			return SWITCH_ODBC_FAIL;
		}

		result = SQLSetEnvAttr(handle->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);

		if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error SetEnv\n");
			SQLFreeHandle(SQL_HANDLE_ENV, handle->env);
			return SWITCH_ODBC_FAIL;
		}

		result = SQLAllocHandle(SQL_HANDLE_DBC, handle->env, &handle->con);

		if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error AllocHDB %d\n", result);
			SQLFreeHandle(SQL_HANDLE_ENV, handle->env);
			return SWITCH_ODBC_FAIL;
		}
		SQLSetConnectAttr(handle->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
	}
	if (handle->state == SWITCH_ODBC_STATE_CONNECTED) {
		switch_odbc_handle_disconnect(handle);
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG1, "Re-connecting %s\n", handle->dsn);
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG1, "Connecting %s\n", handle->dsn);

	if (!strstr(handle->dsn, "DRIVER")) {
		result = SQLConnect(handle->con, (SQLCHAR *) handle->dsn, SQL_NTS, (SQLCHAR *) handle->username, SQL_NTS, (SQLCHAR *) handle->password, SQL_NTS);
	} else {
		SQLCHAR outstr[1024] = { 0 };
		SQLSMALLINT outstrlen = 0;
		result =
			SQLDriverConnect(handle->con, NULL, (SQLCHAR *) handle->dsn, (SQLSMALLINT) strlen(handle->dsn), outstr, sizeof(outstr), &outstrlen,
							 SQL_DRIVER_NOPROMPT);
	}

	if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
		char *err_str;
		if ((err_str = switch_odbc_handle_get_error(handle, NULL))) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "%s\n", err_str);
			free(err_str);
		} else {
			SQLGetDiagRec(SQL_HANDLE_DBC, handle->con, 1, stat, &err, msg, 100, &mlen);
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error SQLConnect=%d errno=%d %s\n", result, (int) err, msg);
		}
		SQLFreeHandle(SQL_HANDLE_ENV, handle->env);
		return SWITCH_ODBC_FAIL;
	}

	result = SQLGetInfo(handle->con, SQL_DRIVER_NAME, (SQLCHAR *) handle->odbc_driver, 255, &valueLength);
	if (result == SQL_SUCCESS || result == SQL_SUCCESS_WITH_INFO) {
		for (i = 0; i < valueLength; ++i)
			handle->odbc_driver[i] = (char) toupper(handle->odbc_driver[i]);
	}

	if (strstr(handle->odbc_driver, "FIREBIRD") != 0 || strstr(handle->odbc_driver, "FB32") != 0 || strstr(handle->odbc_driver, "FB64") != 0) {
		handle->is_firebird = TRUE;
	} else {
		handle->is_firebird = FALSE;
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG1, "Connected to [%s]\n", handle->dsn);
	handle->state = SWITCH_ODBC_STATE_CONNECTED;
	return SWITCH_ODBC_SUCCESS;
#else
	return SWITCH_ODBC_FAIL;
#endif
}
Esempio n. 23
0
/*%
 * create an instance of the driver.  Remember, only 1 copy of the driver's
 * code is ever loaded, the driver has to remember which context it's
 * operating in.  This is done via use of the dbdata argument which is
 * passed into all query functions.
 */
static isc_result_t
odbc_create(const char *dlzname, unsigned int argc, char *argv[],
            void *driverarg, void **dbdata)
{
    isc_result_t result;
    odbc_instance_t *odbc_inst = NULL;
    dbinstance_t *db = NULL;
    SQLRETURN sqlRes;

#ifdef ISC_PLATFORM_USETHREADS
    /* if multi-threaded, we need a few extra variables. */
    int dbcount;
    int i;
    char *endp;

#endif /* ISC_PLATFORM_USETHREADS */

    UNUSED(dlzname);
    UNUSED(driverarg);

#ifdef ISC_PLATFORM_USETHREADS
    /* if debugging, let user know we are multithreaded. */
    isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                  DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(1),
                  "Odbc driver running multithreaded");
#else /* ISC_PLATFORM_USETHREADS */
    /* if debugging, let user know we are single threaded. */
    isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                  DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(1),
                  "Odbc driver running single threaded");
#endif /* ISC_PLATFORM_USETHREADS */

    /* verify we have at least 5 arg's passed to the driver */
    if (argc < 5) {
        isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
                      "Odbc driver requires at least "
                      "4 command line args.");
        return (ISC_R_FAILURE);
    }

    /* no more than 8 arg's should be passed to the driver */
    if (argc > 8) {
        isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
                      "Odbc driver cannot accept more than "
                      "7 command line args.");
        return (ISC_R_FAILURE);
    }

    /* multithreaded build can have multiple DB connections */
#ifdef ISC_PLATFORM_USETHREADS

    /* check how many db connections we should create */
    dbcount = strtol(argv[1], &endp, 10);
    if (*endp != '\0' || dbcount < 0) {
        isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
                      "Odbc driver database connection count "
                      "must be positive.");
        return (ISC_R_FAILURE);
    }

#endif /* ISC_PLATFORM_USETHREADS */

    /* allocate memory for odbc instance */
    odbc_inst = isc_mem_get(ns_g_mctx, sizeof(odbc_instance_t));
    if (odbc_inst == NULL)
        return (ISC_R_NOMEMORY);
    memset(odbc_inst, 0, sizeof(odbc_instance_t));

    /* parse connection string and get paramters. */

    /* get odbc database dsn - required */
    odbc_inst->dsn = (SQLCHAR *) getParameterValue(argv[2],
                     "dsn=");
    if (odbc_inst->dsn == NULL) {
        isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
                      "odbc driver requires a dns parameter.");
        result = ISC_R_FAILURE;
        goto cleanup;
    }
    /* get odbc database username */
    /* if no username was passed, set odbc_inst.user = NULL; */
    odbc_inst->user = (SQLCHAR *) getParameterValue(argv[2],
                      "user="******"pass="******"Odbc driver unable to allocate memory");
            result = ISC_R_NOMEMORY;
            goto cleanup;
        }
        /*set ODBC version = 3 */
        sqlRes = SQLSetEnvAttr(odbc_inst->sql_env,
                               SQL_ATTR_ODBC_VERSION,
                               (void *) SQL_OV_ODBC3, 0);
        if (!sqlOK(sqlRes)) {
            isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                          DNS_LOGMODULE_DLZ, ISC_LOG_INFO,
                          "Unable to configure ODBC environment");
            result = ISC_R_NOMEMORY;
            goto cleanup;
        }
    }

#ifdef ISC_PLATFORM_USETHREADS

    /* allocate memory for database connection list */
    odbc_inst->db = isc_mem_get(ns_g_mctx, sizeof(db_list_t));
    if (odbc_inst->db == NULL) {
        result = ISC_R_NOMEMORY;
        goto cleanup;
    }


    /* initialize DB connection list */
    ISC_LIST_INIT(*odbc_inst->db);

    /* create the appropriate number of database instances (DBI) */
    /* append each new DBI to the end of the list */
    for (i=0; i < dbcount; i++) {

#endif /* ISC_PLATFORM_USETHREADS */

        /* how many queries were passed in from config file? */
        switch(argc) {
        case 5:
            result = build_sqldbinstance(ns_g_mctx, NULL, NULL,
                                         NULL, argv[3], argv[4],
                                         NULL, &db);
            break;
        case 6:
            result = build_sqldbinstance(ns_g_mctx, NULL, NULL,
                                         argv[5], argv[3], argv[4],
                                         NULL, &db);
            break;
        case 7:
            result = build_sqldbinstance(ns_g_mctx, argv[6], NULL,
                                         argv[5], argv[3], argv[4],
                                         NULL, &db);
            break;
        case 8:
            result = build_sqldbinstance(ns_g_mctx, argv[6],
                                         argv[7], argv[5], argv[3],
                                         argv[4], NULL, &db);
            break;
        default:
            /* not really needed, should shut up compiler. */
            result = ISC_R_FAILURE;
        }

        /* unsuccessful?, log err msg and cleanup. */
        if (result != ISC_R_SUCCESS) {
            isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                          DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
                          "Odbc driver could not create "
                          "database instance object.");
            goto cleanup;
        }

#ifdef ISC_PLATFORM_USETHREADS

        /* when multithreaded, build a list of DBI's */
        ISC_LINK_INIT(db, link);
        ISC_LIST_APPEND(*odbc_inst->db, db, link);

#endif

        result = odbc_connect(odbc_inst, (odbc_db_t **) &(db->dbconn));

        if (result != ISC_R_SUCCESS) {

#ifdef ISC_PLATFORM_USETHREADS

            /*
             * if multi threaded, let user know which
             * connection failed.  user could be
             * attempting to create 10 db connections and
             * for some reason the db backend only allows
             * 9.
             */
            isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                          DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
                          "Odbc driver failed to create database "
                          "connection number %u after 3 attempts",
                          i+1);
#else
            isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
                          DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
                          "Odbc driver failed to create database "
                          "connection after 3 attempts");
#endif
            goto cleanup;
        }

#ifdef ISC_PLATFORM_USETHREADS

        /* set DB = null for next loop through. */
        db = NULL;

    }	/* end for loop */

#else
        /* tell odbc_inst about the db connection we just created. */
        odbc_inst->db = db;

#endif

    /* set dbdata to the odbc_instance we created. */
    *dbdata = odbc_inst;

    /* hey, we got through all of that ok, return success. */
    return(ISC_R_SUCCESS);

cleanup:

    destroy_odbc_instance(odbc_inst);

    return result;
}
Esempio n. 24
0
SWITCH_DECLARE(switch_odbc_status_t) switch_odbc_handle_callback_exec_detailed(const char *file, const char *func, int line,
																			   switch_odbc_handle_t *handle,
																			   const char *sql, switch_core_db_callback_func_t callback, void *pdata,
																			   char **err)
{
#ifdef SWITCH_HAVE_ODBC
	SQLHSTMT stmt = NULL;
	SQLSMALLINT c = 0, x = 0;
	SQLLEN m = 0;
	char *err_str = NULL;
	int result;
	int err_cnt = 0;
	int done = 0;

	switch_assert(callback != NULL);

	if (!db_is_up(handle)) {
		goto error;
	}

	if (SQLAllocHandle(SQL_HANDLE_STMT, handle->con, &stmt) != SQL_SUCCESS) {
		err_str = strdup("Unable to SQL allocate handle.");
		goto error;
	}

	if (SQLPrepare(stmt, (unsigned char *) sql, SQL_NTS) != SQL_SUCCESS) {
		err_str = strdup("Unable to prepare SQL statement.");
		goto error;
	}

	result = SQLExecute(stmt);

	if (result != SQL_SUCCESS && result != SQL_SUCCESS_WITH_INFO && result != SQL_NO_DATA) {
		goto error;
	}

	SQLNumResultCols(stmt, &c);
	SQLRowCount(stmt, &m);


	while (!done) {
		int name_len = 256;
		char **names;
		char **vals;
		int y = 0;

		result = SQLFetch(stmt);

		if (result != SQL_SUCCESS) {
			if (result != SQL_NO_DATA) {
				err_cnt++;
			}
			break;
		}

		names = calloc(c, sizeof(*names));
		vals = calloc(c, sizeof(*vals));

		switch_assert(names && vals);

		for (x = 1; x <= c; x++) {
			SQLSMALLINT NameLength = 0, DataType = 0, DecimalDigits = 0, Nullable = 0;
			SQLULEN ColumnSize = 0;
			names[y] = malloc(name_len);
			memset(names[y], 0, name_len);

			SQLDescribeCol(stmt, x, (SQLCHAR *) names[y], (SQLSMALLINT) name_len, &NameLength, &DataType, &ColumnSize, &DecimalDigits, &Nullable);

			if (!ColumnSize) {
				ColumnSize = 255;
			}
			ColumnSize++;

			vals[y] = malloc(ColumnSize);
			memset(vals[y], 0, ColumnSize);
			SQLGetData(stmt, x, SQL_C_CHAR, (SQLCHAR *) vals[y], ColumnSize, NULL);
			y++;
		}

		if (callback(pdata, y, vals, names)) {
			done = 1;
		}

		for (x = 0; x < y; x++) {
			free(names[x]);
			free(vals[x]);
		}
		free(names);
		free(vals);
	}

	SQLFreeHandle(SQL_HANDLE_STMT, stmt);

	if (!err_cnt) {
		return SWITCH_ODBC_SUCCESS;
	}

  error:

	if (stmt) {
		err_str = switch_odbc_handle_get_error(handle, stmt);
		SQLFreeHandle(SQL_HANDLE_STMT, stmt);
	}

	if (err_str) {
		switch_log_printf(SWITCH_CHANNEL_ID_LOG, file, func, line, NULL, SWITCH_LOG_ERROR, "ERR: [%s]\n[%s]\n", sql, switch_str_nil(err_str));
		if (err) {
			*err = err_str;
		} else {
			free(err_str);
		}
	}

#endif
	return SWITCH_ODBC_FAIL;
}
Esempio n. 25
0
/* Changed ... Have to implement the same for translators */
void
adddrivers_to_list (ControlRef widget, WindowRef dlg, BOOL addNotify)
{
  wchar_t drvdesc[1024], drvattrs[1024], driver[1024];
  DataBrowserItemID item = DBITEM_ID + 1;
  DataBrowserCallbacks dbCallbacks;
  ThemeDrawingState outState = NULL;
  UInt16 colSize[5] = { 150, 150, 100, 50 , 50};
  void *handle;
  SInt16 outBaseline;
  Point ioBound;
  struct stat _stat;
  SQLSMALLINT len, len1;
  SQLRETURN ret;
  HENV henv, drv_henv;
  HDBC drv_hdbc;
  pSQLGetInfoFunc funcHdl;
  pSQLAllocHandle allocHdl;
  pSQLAllocEnv allocEnvHdl = NULL;
  pSQLAllocConnect allocConnectHdl = NULL;
  pSQLFreeHandle freeHdl;
  pSQLFreeEnv freeEnvHdl;
  pSQLFreeConnect freeConnectHdl;
  char *_drv_u8 = NULL;
  int i;

  if (!widget)
    return;

  GetThemeDrawingState (&outState);

  /* Install an event handler on the component databrowser */
  dbCallbacks.version = kDataBrowserLatestCallbacks;
  InitDataBrowserCallbacks (&dbCallbacks);

  if (addNotify)
    dbCallbacks.u.v1.itemNotificationCallback =
      NewDataBrowserItemNotificationUPP (drivers_notification_item);

  /* On Mac OS X 10.0.x : clientDataCallback */
  dbCallbacks.u.v1.itemDataCallback =
      NewDataBrowserItemDataUPP (drivers_getset_item);
  SetDataBrowserCallbacks (widget, &dbCallbacks);
  /* Begin the draw of the data browser */
  SetDataBrowserTarget (widget, DBITEM_ID);

  /* Make the clean up */
  for (i = 0; i < Drivers_nrows; i++, item++)
    {
      CFRelease (Drivers_array[0][i]);
      Drivers_array[0][i] = NULL;
      CFRelease (Drivers_array[1][i]);
      Drivers_array[1][i] = NULL;
      CFRelease (Drivers_array[2][i]);
      Drivers_array[2][i] = NULL;
      CFRelease (Drivers_array[3][i]);
      Drivers_array[3][i] = NULL;
      CFRelease (Drivers_array[4][i]);
      Drivers_array[4][i] = NULL;
      RemoveDataBrowserItems (widget, DBITEM_ID, 1, &item, DBNAME_ID);
    }

  /* Global Initialization */
  Drivers_nrows = 0;
  item = DBITEM_ID + 1;

  /* Create a HENV to get the list of drivers then */
  ret = SQLAllocHandle (SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
  if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO)
    {
      _iodbcdm_nativeerrorbox (dlg, henv, SQL_NULL_HANDLE, SQL_NULL_HANDLE);
      goto end;
    }

  /* Set the version ODBC API to use */
  SQLSetEnvAttr (henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3,
      SQL_IS_UINTEGER);

  /* Get the list of drivers */
  ret =
      SQLDriversW (henv, SQL_FETCH_FIRST, drvdesc, sizeof (drvdesc)/sizeof(wchar_t),
        &len, drvattrs, sizeof (drvattrs)/sizeof(wchar_t), &len1);
  if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO && ret != SQL_NO_DATA)
    {
      _iodbcdm_nativeerrorbox (dlg, henv, SQL_NULL_HANDLE, SQL_NULL_HANDLE);
      goto error;
    }

  while (ret != SQL_NO_DATA)
    {
      Drivers_array[0][Drivers_nrows] = convert_wchar_to_CFString(drvdesc);

      /* Get the driver library name */
      SQLSetConfigMode (ODBC_BOTH_DSN);
      SQLGetPrivateProfileStringW (drvdesc, L"Driver", L"", driver,
	  sizeof (driver)/sizeof(wchar_t), L"odbcinst.ini");
      if (driver[0] == L'\0')
	SQLGetPrivateProfileStringW (L"Default", L"Driver", L"", driver,
	    sizeof (driver)/sizeof(wchar_t), L"odbcinst.ini");
      if (driver[0] == L'\0')
	{
	  if (Drivers_array[0][Drivers_nrows])
            {
              CFRelease (Drivers_array[0][Drivers_nrows]);
              Drivers_array[0][Drivers_nrows] = NULL;
            }
	  goto skip;
	}

      Drivers_array[1][Drivers_nrows] = convert_wchar_to_CFString(driver);

      /* Alloc a connection handle */
      drv_hdbc = NULL;
      drv_henv = NULL;

      _drv_u8 = (char *) dm_SQL_WtoU8((SQLWCHAR*)driver, SQL_NTS);
      if (_drv_u8 == NULL)
        goto skip;

      if ((handle = DLL_OPEN(_drv_u8)) != NULL)
        {
          if ((allocHdl = (pSQLAllocHandle)DLL_PROC(handle, "SQLAllocHandle")) != NULL)
            {
              ret = allocHdl(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &drv_henv);
	      if (ret == SQL_ERROR) goto nodriverver;
              ret = allocHdl(SQL_HANDLE_DBC, drv_henv, &drv_hdbc);
	      if (ret == SQL_ERROR) goto nodriverver;
            }
          else
            {
              if ((allocEnvHdl = (pSQLAllocEnv)DLL_PROC(handle, "SQLAllocEnv")) != NULL)
                {
                  ret = allocEnvHdl(&drv_henv);
	          if (ret == SQL_ERROR) goto nodriverver;
                }
              else goto nodriverver;

              if ((allocConnectHdl = (pSQLAllocConnect)DLL_PROC(handle, "SQLAllocConnect")) != NULL)
                {
                  ret = allocConnectHdl(drv_henv, &drv_hdbc);
	          if (ret == SQL_ERROR) goto nodriverver;
                }
              else goto nodriverver;
            }

	  /*
	   *  Use SQLGetInfoA for Unicode drivers
	   *  and SQLGetInfo  for ANSI drivers
	   */
          funcHdl = (pSQLGetInfoFunc)DLL_PROC(handle, "SQLGetInfoA");
	  if (!funcHdl)
	      funcHdl = (pSQLGetInfoFunc)DLL_PROC(handle, "SQLGetInfo");

	  if (funcHdl)
            {
              /* Retrieve some informations */
              ret = funcHdl (drv_hdbc, SQL_DRIVER_VER, drvattrs, sizeof(drvattrs), &len);
              if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO)
                {
		  char *p = drvattrs;

                  /* Find the description if one provided */
		  for (; *p ; p++) 
		    {
		      if (*p == ' ')
		        {
			  *p++ = '\0';
			  break;
			}
		    }

		  /*
		   * Store Version
		   */
                  Drivers_array[2][Drivers_nrows] = CFStringCreateWithCString(NULL, (char *)drvattrs, kCFStringEncodingUTF8);
                }
              else goto nodriverver;
            }
	  else if ((funcHdl = (pSQLGetInfoFunc)DLL_PROC(handle, "SQLGetInfoW")) != NULL) 
	    {
              /* Retrieve some informations */
              ret = funcHdl (drv_hdbc, SQL_DRIVER_VER, drvattrs, sizeof(drvattrs), &len);
              if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO)
                {
		  wchar_t *p = drvattrs;

                  /* Find the description if one provided */
		  for (; *p ; p++) 
		    {
		      if (*p == L' ')
		        {
			  *p++ = L'\0';
			  break;
			}
		    }

		  /*
		   * Store Version
		   */
                  Drivers_array[2][Drivers_nrows] = convert_wchar_to_CFString(drvattrs);
                }
              else goto nodriverver;
	        
	    }
          else goto nodriverver;
        }
      else
        {
nodriverver:
          Drivers_array[2][Drivers_nrows] = CFStringCreateWithCString(NULL,
            "##.##", kCFStringEncodingUTF8);
        }

      if(drv_hdbc || drv_henv)
        {
          if(allocConnectHdl &&
            (freeConnectHdl = (pSQLFreeConnect)DLL_PROC(handle, "SQLFreeConnect")) != NULL)
            { freeConnectHdl(drv_hdbc); drv_hdbc = NULL; }

          if(allocEnvHdl &&
            (freeEnvHdl = (pSQLFreeEnv)DLL_PROC(handle, "SQLFreeEnv")) != NULL)
            { freeEnvHdl(drv_henv); drv_henv = NULL; }
        }

      if ((drv_hdbc || drv_henv) &&
         (freeHdl = (pSQLFreeHandle)DLL_PROC(handle, "SQLFreeHandle")) != NULL)
        {
          if(drv_hdbc) freeHdl(SQL_HANDLE_DBC, drv_hdbc);
          if(drv_henv) freeHdl(SQL_HANDLE_ENV, drv_henv);
        }

      DLL_CLOSE(handle);

      /* Get the size and date of the driver */
      if (!stat (_drv_u8, &_stat))
	{
          CFStringRef strRef;
	  struct tm drivertime;
	  char buf[100];

          Drivers_array[3][Drivers_nrows] = 
            CFStringCreateWithFormat(NULL, NULL,
              strRef = CFStringCreateWithCString(NULL, "%d Kb", kCFStringEncodingUTF8),
              (int) (_stat.st_size / 1024));
	  CFRelease(strRef);

	  localtime_r (&_stat.st_mtime, &drivertime);
	  strftime (buf, sizeof (buf), "%c", &drivertime);
	  Drivers_array[4][Drivers_nrows] = CFStringCreateWithCString(NULL, 
	  	buf, kCFStringEncodingUTF8);
        }
      else
        {
	    Drivers_array[3][Drivers_nrows] = CFStringCreateWithCString(NULL,
	      "-", kCFStringEncodingUTF8);
	    Drivers_array[4][Drivers_nrows] = CFStringCreateWithCString(NULL,
	      "-", kCFStringEncodingUTF8);
	}

      for(i = 0 ; i < 5 ; i++)
        {
          GetThemeTextDimensions (Drivers_array[i][Drivers_nrows], kThemeSystemFont,
            kThemeStateActive, false, &ioBound, &outBaseline);
          if(colSize[i] < ioBound.h) colSize[i] = ioBound.h;
        }

      AddDataBrowserItems (widget, DBITEM_ID, 1, &item, DBNAME_ID);
      item++;
      Drivers_nrows++;

      /* Process next one */
    skip:
      MEM_FREE (_drv_u8);
      _drv_u8 = NULL;

      ret = SQLDriversW (henv, SQL_FETCH_NEXT, drvdesc,
	  sizeof (drvdesc)/sizeof(wchar_t), &len, drvattrs,
	  sizeof (drvattrs)/sizeof(wchar_t), &len1);
      if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO && ret != SQL_NO_DATA)
	{
	  _iodbcdm_nativeerrorbox (dlg, henv, SQL_NULL_HANDLE,
	      SQL_NULL_HANDLE);
	  goto error;
	}
    }

error:
  /* Clean all that */
  SQLFreeHandle (SQL_HANDLE_ENV, henv);

end:
  ActivateControl (widget);
  /* Resize the columns to have a good look */
  SetDataBrowserTableViewNamedColumnWidth (widget, DBNAME_ID, colSize[0] + 20);
  SetDataBrowserTableViewNamedColumnWidth (widget, DBFILE_ID, colSize[1] + 20);
  SetDataBrowserTableViewNamedColumnWidth (widget, DBVERSION_ID, colSize[2] + 20);
  SetDataBrowserTableViewNamedColumnWidth (widget, DBSIZE_ID, colSize[3] + 20);
  SetDataBrowserTableViewNamedColumnWidth (widget, DBDATE_ID, colSize[4] + 20);
  DrawOneControl (widget);
  /* Remove the DataBrowser callback */
  SetDataBrowserCallbacks (NULL, &dbCallbacks);
  if(outState) DisposeThemeDrawingState (outState);
}
Esempio n. 26
0
//*************************************************************************
int main()
{
  SQLHENV env;
  SQLHDBC dbc;
  SQLHSTMT stmt;
  SQLRETURN ret;
  SQLCHAR outstr[1024];
  SQLSMALLINT outstrlen;
  
  // Aloocate an environment handle
  ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env);
  checkrc(ret,__LINE__);
  
   //we need odbc3 support
   SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);
   
  //ALLOCATE A Connection handle
  ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc);
  checkrc(ret,__LINE__);
    
  // connect to the DSN mydsn
   ret = SQLConnect (dbc,
                   (SQLCHAR *) "DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;"),
                   (SQLCHAR *) "root",
                   (SQLSMALLINT) strlen ("root"),
                   (SQLCHAR *) "manager",
                   (SQLSMALLINT) strlen (""));


  if(SQL_SUCCEEDED(ret))
  {
     printf("\nConnected to the Data Source..\n");
       
     
  }
   else
   {
        printf("connection failed\n");
        ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
        checkrc(ret,__LINE__); 
        ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
        checkrc(ret,__LINE__);
        return 1;
   }

   ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt);
   checkrc(ret,__LINE__);

   SQLCHAR table[100]="CREATE TABLE EMP(EID INT,SALARY INT)";
   
   ret = SQLPrepare(stmt,table,SQL_NTS);
   checkrc(ret,__LINE__);

   ret = SQLDisconnect(dbc);
   checkrc(ret,__LINE__);
   
   //AFTER CLOSE THE CONNECTION ,CALL execute
      
   ret = SQLExecute(stmt);
   int rettype = ret;
   if(ret )
   printf("After closing the connection, Execution failed\n"); 
   
      
   ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
   checkrc(ret,__LINE__);
  
   if(rettype ==0)return 1;
     

  return 0;
}         
Esempio n. 27
0
 StatementHolder(Connection &conn)
 {
   if (SQLAllocHandle(SQL_HANDLE_STMT, conn.GetHolder().GetHandle(), &Stmt) != SQL_SUCCESS)
     throw StatementException("Error alloc statement", srErrorAllocStatement);
 }
Esempio n. 28
0
static SQLHSTMT execute_cb(struct odbc_obj *obj, void *data)
{
    struct ast_cdr *cdr = data;
    SQLRETURN ODBC_res;
    char sqlcmd[2048] = "", timestr[128];
    struct ast_tm tm;
    SQLHSTMT stmt;

    ast_localtime(&cdr->start, &tm, ast_test_flag(&config, CONFIG_USEGMTIME) ? "GMT" : NULL);
    ast_strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);

    if (ast_test_flag(&config, CONFIG_LOGUNIQUEID)) {
        snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s "
                 "(calldate,clid,src,dst,dcontext,channel,dstchannel,lastapp,"
                 "lastdata,duration,billsec,disposition,amaflags,accountcode,uniqueid,userfield) "
                 "VALUES ({ts '%s'},?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", table, timestr);
    } else {
        snprintf(sqlcmd,sizeof(sqlcmd),"INSERT INTO %s "
                 "(calldate,clid,src,dst,dcontext,channel,dstchannel,lastapp,lastdata,"
                 "duration,billsec,disposition,amaflags,accountcode) "
                 "VALUES ({ts '%s'},?,?,?,?,?,?,?,?,?,?,?,?,?)", table, timestr);
    }

    ODBC_res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);

    if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) {
        ast_verb(11, "cdr_odbc: Failure in AllocStatement %d\n", ODBC_res);
        SQLFreeHandle(SQL_HANDLE_STMT, stmt);
        return NULL;
    }

    SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->clid), 0, cdr->clid, 0, NULL);
    SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->src), 0, cdr->src, 0, NULL);
    SQLBindParameter(stmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->dst), 0, cdr->dst, 0, NULL);
    SQLBindParameter(stmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->dcontext), 0, cdr->dcontext, 0, NULL);
    SQLBindParameter(stmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->channel), 0, cdr->channel, 0, NULL);
    SQLBindParameter(stmt, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->dstchannel), 0, cdr->dstchannel, 0, NULL);
    SQLBindParameter(stmt, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->lastapp), 0, cdr->lastapp, 0, NULL);
    SQLBindParameter(stmt, 8, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->lastdata), 0, cdr->lastdata, 0, NULL);

    if (ast_test_flag(&config, CONFIG_HRTIME)) {
        double hrbillsec = 0.0;
        double hrduration;

        if (!ast_tvzero(cdr->answer)) {
            hrbillsec = (double) ast_tvdiff_us(cdr->end, cdr->answer) / 1000000.0;
        }
        hrduration = (double) ast_tvdiff_us(cdr->end, cdr->start) / 1000000.0;

        SQLBindParameter(stmt, 9, SQL_PARAM_INPUT, SQL_C_DOUBLE, SQL_FLOAT, 0, 0, &hrduration, 0, NULL);
        SQLBindParameter(stmt, 10, SQL_PARAM_INPUT, SQL_C_DOUBLE, SQL_FLOAT, 0, 0, &hrbillsec, 0, NULL);
    } else {
        SQLBindParameter(stmt, 9, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->duration, 0, NULL);
        SQLBindParameter(stmt, 10, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->billsec, 0, NULL);
    }

    if (ast_test_flag(&config, CONFIG_DISPOSITIONSTRING))
        SQLBindParameter(stmt, 11, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(ast_cdr_disp2str(cdr->disposition)) + 1, 0, ast_cdr_disp2str(cdr->disposition), 0, NULL);
    else
        SQLBindParameter(stmt, 11, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->disposition, 0, NULL);
    SQLBindParameter(stmt, 12, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, &cdr->amaflags, 0, NULL);
    SQLBindParameter(stmt, 13, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->accountcode), 0, cdr->accountcode, 0, NULL);

    if (ast_test_flag(&config, CONFIG_LOGUNIQUEID)) {
        SQLBindParameter(stmt, 14, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->uniqueid), 0, cdr->uniqueid, 0, NULL);
        SQLBindParameter(stmt, 15, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(cdr->userfield), 0, cdr->userfield, 0, NULL);
    }

    ODBC_res = SQLExecDirect(stmt, (unsigned char *)sqlcmd, SQL_NTS);

    if ((ODBC_res != SQL_SUCCESS) && (ODBC_res != SQL_SUCCESS_WITH_INFO)) {
        ast_verb(11, "cdr_odbc: Error in ExecDirect: %d\n", ODBC_res);
        SQLFreeHandle(SQL_HANDLE_STMT, stmt);
        return NULL;
    }

    return stmt;
}
Esempio n. 29
0
bool CODBCRecordset::InsertBinary(const CString& strQuery, const u8* pData, int nSize)
{
	if (!m_pDatabase->IsOpen())
	{
		assert(0);
		return false;
	}

	if ((0 == strQuery.GetLength()) || 0 == pData)
		return false;

	if (8000 < nSize)
		return false;

	HSTMT		hStmt;
	SQLTCHAR*	pWriteBuff;
	SQLLEN  ind = SQL_DATA_AT_EXEC;

	if (SQL_ERROR == SQLAllocHandle(SQL_HANDLE_STMT, m_pDatabase->GetConn(), &hStmt))
	{
		return false;
	}

	if (SQL_ERROR == SQLPrepare(hStmt, SQLData(strQuery), SQL_NTS))
	{
		return false;
	}

	if (SQL_ERROR == SQLBindParameter(hStmt, 1, SQL_PARAM_INPUT,
		SQL_C_BINARY, SQL_BINARY,
		nSize, 0, (SQLPOINTER)pData, nSize, &ind))
	{
		return false;
	}

	if (SQL_ERROR == SQLExecute(hStmt))
	{
		return false;
	}

	if (SQL_ERROR == SQLParamData(hStmt, (SQLPOINTER*)&pWriteBuff))
	{
		return false;
	}

	int			nWrSize;
	int			len;
	SQLRETURN	sqlRet;

	for (nWrSize = 0; nWrSize < nSize; nWrSize += BINARY_CHUNK_SIZE, pWriteBuff += BINARY_CHUNK_SIZE)
	{
		if (nWrSize + BINARY_CHUNK_SIZE < nSize)
			len = BINARY_CHUNK_SIZE;
		else
			len = nSize - nWrSize;

		sqlRet = SQLPutData(hStmt, (SQLPOINTER)pWriteBuff, len);
	}

	if (SQL_ERROR == sqlRet)
	{
		return false;
	}

	if (SQL_ERROR == SQLParamData(hStmt, (SQLPOINTER*)&pWriteBuff))
	{
		return false;
	}

	SQLFreeHandle(SQL_HANDLE_STMT, hStmt);

	return true;
}
Esempio n. 30
0
void
adddrivers_to_list (GtkWidget *widget, GtkWidget *dlg)
{
  SQLCHAR drvdesc[1024], drvattrs[1024], driver[1024], size[64];
  SQLCHAR *data[4];
  void *handle;
  struct stat _stat;
  SQLSMALLINT len, len1;
  SQLRETURN ret;
  HENV henv, drv_henv;
  HDBC drv_hdbc;
  pSQLGetInfoFunc funcHdl;
  pSQLAllocHandle allocHdl;
  pSQLAllocEnv allocEnvHdl = NULL;
  pSQLAllocConnect allocConnectHdl = NULL;
  pSQLFreeHandle freeHdl;
  pSQLFreeEnv freeEnvHdl;
  pSQLFreeConnect freeConnectHdl;

  if (!GTK_IS_CLIST (widget))
    return;
  gtk_clist_clear (GTK_CLIST (widget));

  /* Create a HENV to get the list of drivers then */
  ret = SQLAllocHandle (SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
  if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO)
    {
      _iodbcdm_nativeerrorbox (dlg, henv, SQL_NULL_HANDLE, SQL_NULL_HANDLE);
      goto end;
    }

  /* Set the version ODBC API to use */
  SQLSetEnvAttr (henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3,
      SQL_IS_INTEGER);

  /* Get the list of drivers */
  ret =
      SQLDrivers (henv, SQL_FETCH_FIRST, drvdesc,
      sizeof (drvdesc) / sizeof (SQLTCHAR), &len, drvattrs,
      sizeof (drvattrs) / sizeof (SQLTCHAR), &len1);
  if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO
      && ret != SQL_NO_DATA)
    {
      _iodbcdm_nativeerrorbox (dlg, henv, SQL_NULL_HANDLE, SQL_NULL_HANDLE);
      goto error;
    }

  while (ret != SQL_NO_DATA)
    {
      data[0] = drvdesc;

      /* Get the driver library name */
      SQLSetConfigMode (ODBC_BOTH_DSN);
      SQLGetPrivateProfileString (drvdesc, "Driver", "", driver,
	  sizeof (driver) / sizeof (SQLTCHAR), "odbcinst.ini");
      if (driver[0] == '\0')
	SQLGetPrivateProfileString ("Default", "Driver", "", driver,
	    sizeof (driver) / sizeof (SQLTCHAR), "odbcinst.ini");
      if (driver[0] == '\0')
	{
	  data[0] = NULL;
	  goto skip;
	}

      data[1] = driver;

      drv_hdbc = NULL;
      drv_henv = NULL;

      if ((handle = (void *) DLL_OPEN (driver)) != NULL)
	{
	  if ((allocHdl =
		  (pSQLAllocHandle) DLL_PROC (handle,
		      "SQLAllocHandle")) != NULL)
	    {
	      ret = allocHdl (SQL_HANDLE_ENV, SQL_NULL_HANDLE, &drv_henv);
	      if (ret == SQL_ERROR)
		goto nodriverver;
	      ret = allocHdl (SQL_HANDLE_DBC, drv_henv, &drv_hdbc);
	      if (ret == SQL_ERROR)
		goto nodriverver;
	    }
	  else
	    {
	      if ((allocEnvHdl =
		      (pSQLAllocEnv) DLL_PROC (handle,
			  "SQLAllocEnv")) != NULL)
		{
		  ret = allocEnvHdl (&drv_henv);
		  if (ret == SQL_ERROR)
		    goto nodriverver;
		}
	      else
		goto nodriverver;

	      if ((allocConnectHdl =
		      (pSQLAllocConnect) DLL_PROC (handle,
			  "SQLAllocConnect")) != NULL)
		{
		  ret = allocConnectHdl (drv_henv, &drv_hdbc);
		  if (ret == SQL_ERROR)
		    goto nodriverver;
		}
	      else
		goto nodriverver;
	    }

	  if ((funcHdl =
		  (pSQLGetInfoFunc) DLL_PROC (handle, "SQLGetInfo")) != NULL)
	    {
	      /* Retrieve some information */
	      ret =
		  funcHdl (drv_hdbc, SQL_DRIVER_VER, drvattrs,
		  sizeof (drvattrs), &len);
	      if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO)
		{
		  unsigned int z;
		  /* Drop the description if one provided */
		  for (z = 0; ((char *) drvattrs)[z]; z++)
		    if (((char *) drvattrs)[z] == ' ')
		      ((char *) drvattrs)[z] = '\0';
		  data[2] = drvattrs;
		}
	      else
		goto nodriverver;
	    }
	  else
	    goto nodriverver;
	}
      else
	{
	nodriverver:
	  data[2] = "##.##";
	}

      if (drv_hdbc || drv_henv)
	{
	  if (allocConnectHdl &&
	      (freeConnectHdl =
		  (pSQLFreeConnect) DLL_PROC (handle,
		      "SQLFreeConnect")) != NULL)
	    {
	      freeConnectHdl (drv_hdbc);
	      drv_hdbc = NULL;
	    }

	  if (allocEnvHdl &&
	      (freeEnvHdl =
		  (pSQLFreeEnv) DLL_PROC (handle, "SQLFreeEnv")) != NULL)
	    {
	      freeEnvHdl (drv_henv);
	      drv_henv = NULL;
	    }
	}

      if ((drv_hdbc || drv_henv) &&
	  (freeHdl =
	      (pSQLFreeHandle) DLL_PROC (handle, "SQLFreeHandle")) != NULL)
	{
	  if (drv_hdbc)
	    freeHdl (SQL_HANDLE_DBC, drv_hdbc);
	  if (drv_henv)
	    freeHdl (SQL_HANDLE_ENV, drv_henv);
	}

      if (handle)
        DLL_CLOSE (handle);

      /* Get the size of the driver */
      if (!stat (driver, &_stat))
	{
	  sprintf (size, "%d Kb", (int) (_stat.st_size / 1024));
	  data[3] = size;
	}
      else
	data[3] = "-";

      gtk_clist_append (GTK_CLIST (widget), data);

    skip:
      ret = SQLDrivers (henv, SQL_FETCH_NEXT, drvdesc,
	  sizeof (drvdesc) / sizeof (SQLTCHAR), &len, drvattrs,
	  sizeof (drvattrs) / sizeof (SQLTCHAR), &len1);
      if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO
	  && ret != SQL_NO_DATA)
	{
	  _iodbcdm_nativeerrorbox (dlg, henv, SQL_NULL_HANDLE,
	      SQL_NULL_HANDLE);
	  goto error;
	}
    }

error:
  /* Clean all that */
  SQLFreeHandle (SQL_HANDLE_ENV, henv);

end:
  if (GTK_CLIST (widget)->rows > 0)
    {
      gtk_clist_columns_autosize (GTK_CLIST (widget));
      gtk_clist_sort (GTK_CLIST (widget));
    }
}