#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "libpq-fe.h"

#define BUFFER_SIZE 100

static void exit_gracefully(PGconn* connPtr)
{
	PQfinish(connPtr);
	exit(1);
}

int main(int argc, char argv[])
{
	char buffer[BUFFER_SIZE];
	int nCounterValue = 0;
	PGresult* resPtr;
	const char* connectInfoPtr = "dbname = postgres";
	PGconn* dbConnPtr = PQconnectdb(connectInfoPtr);

	if( PQstatus(dbConnPtr) != CONNECTION_OK)
	{
		printf("\nConnection to postgres DB failed: %s", PQerrorMessage(dbConnPtr));
		exit_gracefully(dbConnPtr);
	}

	printf("\nConnection to the postgres DB succeeded\n");
	int nMAXCounter = 20000;
	while(nMAXCounter--)
	{
		/* Start the transaction block */
		resPtr = PQexec(dbConnPtr, "BEGIN");
		if( PQresultStatus(resPtr) != PGRES_COMMAND_OK )
		{
			printf("Could not start the transaction: %s\n", PQerrorMessage(dbConnPtr));
			PQclear(resPtr);
			exit_gracefully(dbConnPtr);
		}
		PQclear(resPtr); /* Release the memory */

		resPtr = PQexec(dbConnPtr, "SELECT COUNTER FROM COUNTER_TABLE");
		if(PQresultStatus(resPtr) != PGRES_TUPLES_OK)
		{
			printf("SELECT failed: %s", PQerrorMessage(dbConnPtr));
			PQclear(resPtr);
			exit_gracefully(dbConnPtr);
		}

		int nColumns = PQnfields(resPtr);
		/*
		for(int nCount = 0; nCount < nColumns; nCount++)
		{
			printf("%-15s", PQfname(resPtr, nCount));
		}
		printf("\n");
		*/

		/* Get the counter value */
		for (int nRow = 0; nRow < PQntuples(resPtr); nRow++ )
		{
			for(int nCol = 0; nCol < nColumns; nCol++)
			{
				nCounterValue = atol (PQgetvalue(resPtr, nCol,nRow));
				printf("CounterValue after fetch: %d", nCounterValue);
			}
		}
		PQclear(resPtr);

		/* Update the counter value after incrementing */
		nCounterValue++;
		sprintf(buffer,"UPDATE COUNTER_TABLE SET COUNTER = %d", nCounterValue);
		resPtr = PQexec(dbConnPtr, buffer));
		if(PQresultStatus(resPtr) != PGRES_COMMAND_OK)
		{
			printf("UPDATE failed for counter %d: %s", nCounterValue, PQerrorMessage(dbConnPtr));
			PQclear(resPtr);
			exit_gracefully(dbConnPtr);
		}
		printf("\t\tUpdated Counter %d", nCounterValue);
		PQclear(resPtr);
	}
	/* Close the DB connection */
	PQfinish(dnConnPtr);
	printf("\n\n");
	return 0;
}