#include <stdio.h>
#include <stdlib.h>

#include <pthread.h>

#include "common.h"

struct thread_data
{
	SQLHDBC conn;
};

SQLHSTMT hstmt;

/* this thread runs a long query */
void *thread1_main(void *d)
{
	SQLRETURN rc;

	printf("1: calling SQLExecute\n");
	rc = SQLExecute(hstmt);
	
	CHECK_STMT_RESULT(rc, "1: SQLExecute failed", hstmt);
	print_result(hstmt);

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

/* this thread cancels the first thread's query */
void *thread2_main(void *d)
{
	SQLRETURN rc;

	sleep(2);

	printf("2: canceling first query\n");
	rc = SQLCancel(hstmt);
	if (rc == SQL_SUCCESS)
		printf("2: canceled\n");
	else if (rc == SQL_ERROR)
		printf("2: SQLCancel failed\n");
	else
		printf("2: unexpected return code from SQLCancel: %d\n", rc);
}

int main(int argc, char **argv)
{
	SQLRETURN rc;
	char *param1;
	SQLLEN cbParam1;
	int			i;
#define NTHREADS 2
	char		errstr[100];
	pthread_t	thread1;
	pthread_t	thread2;
	void *retval;
	test_connect();

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

	rc = SQLPrepare(hstmt, (SQLCHAR *) "SELECT pg_sleep(1000)", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);

	if (pthread_create(&thread1, NULL, thread1_main, NULL))
	{
		printf("error creating thread\n");
		exit(1);
	}

	if (pthread_create(&thread2, NULL, thread2_main, NULL))
	{
		printf("error creating thread\n");
		exit(1);
	}

	if (pthread_join(thread1, &retval) != 0)
	{
		printf("error joining thread\n");
		exit(1);
	}
	if (pthread_join(thread2, &retval) != 0)
	{
		printf("error joining thread\n");
		exit(1);
	}

	return 0;
}
