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

#include <pthread.h>

#include "common.h"

struct stmt_freeing_thread_data
{
	SQLHDBC conn;
	HSTMT hstmt;
};

void *stmt_freeing_thread_main(void *hstmt)
{
	struct stmt_freeing_thread_data *data =
		(struct stmt_freeing_thread_data *) hstmt;
	SQLRETURN rc;

	sleep(2);

	rc = SQLFreeStmt(data->hstmt, SQL_DROP);
	if (!SQL_SUCCEEDED(rc))
	{
		print_diag("SQLFreeStmt failed", SQL_HANDLE_DBC, data->conn);
		exit(1);
	}
}

int main(int argc, char **argv)
{
	SQLRETURN rc;
	HSTMT hstmt = SQL_NULL_HSTMT;
	HSTMT hstmt2 = SQL_NULL_HSTMT;
	char *param1;
	SQLLEN cbParam1;
	int			i;
	char		errstr[100];
	pthread_t stmt_freeing_thread;
	struct stmt_freeing_thread_data thread_data;
	
	test_connect();

	rc=SQLSetConnectAttr( conn,SQL_ATTR_AUTOCOMMIT,
						  (void*) SQL_AUTOCOMMIT_OFF, SQL_NTS);
	if (!SQL_SUCCEEDED(rc))
	{
		print_diag("SQLSetConnectAttr failed", SQL_HANDLE_STMT, hstmt);
		exit(1);
	}

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

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

	/* Prepare a statement */
	rc = SQLPrepare(hstmt, (SQLCHAR *) "SELECT 'foo'", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLPrepare failed", hstmt);

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

    rc = SQLEndTran( SQL_HANDLE_DBC, conn, SQL_COMMIT);
	if (!SQL_SUCCEEDED(rc))
	{
		print_diag("SQLEndTran failed", SQL_HANDLE_DBC, conn);
		exit(1);
	}

	/*
	 * Launch a new thread that will free the statement after two seconds,
	 * while we're busy executing another statement
	 */
	thread_data.conn = conn;
	thread_data.hstmt = hstmt;
	if (pthread_create(&stmt_freeing_thread, NULL,
					   stmt_freeing_thread_main, &thread_data))
	{
		printf("error creating thread\n");
		exit(1);
	}
	/*
	 * Before the other thread free's the first statement, begin a new query
	 * using a the second statement on the same connection.
	 */
	rc = SQLExecDirect(hstmt2, (SQLCHAR *) "SELECT pg_sleep(5)", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);

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

	/* the thread freeing the first statmenet should be finished by now */
	if (pthread_join(stmt_freeing_thread, NULL))
	{
		printf("error joining thread\n");
		exit(1);
	}

	/* Verify that the prepared statement was deallocated */
	printf("Querying pg_prepared_statement to check if all prepared statements\n");
	printf("were DEALLOCATEd correctly. The result set should be empty.\n");

	rc = SQLExecDirect(hstmt2, (SQLCHAR *) "SELECT * FROM pg_prepared_statements", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt2);
	print_result(hstmt2);
	printf("\n");

	/* Clean up */
	test_disconnect();

	return 0;
}
