# include <libpq-fe.h>
# include <pthread.h>
# include <iostream>
# include <string>
#include <exception>

using namespace std;

#define NUM_THREADS 5

void *connect(void* threadid)
{
    int *id_ptr, taskid;
    id_ptr = (int *) threadid;
    taskid = *id_ptr;

    PGconn * conn;
    PGresult * res;
    conn = PQconnectdb("dbname=dbexpress host=lucifer user=sdc");
    if(PQstatus(conn) == CONNECTION_OK)
    {
	cout << endl << "Connection Made";
	res = PQexec(conn, "Begin transaction");
	cout << endl << "Status is : " << PQresStatus(PQresultStatus(res));
	cout << endl << "Result message : "<< PQresultErrorMessage(res);
	PQclear(res);
	
	res = PQexec(conn, "select insert_patient('sur', '1', '1999-10-10', 'key')");
	cout << endl << "Status is : " << PQresStatus(PQresultStatus(res));
	cout << endl << "Result message : "<< PQresultErrorMessage(res);
	
	switch (PQresultStatus(res))
	{
	    case PGRES_TUPLES_OK:
	    {
		int n = 0;
		int r = 0;
		int nrows = PQntuples(res);
		int nfields = PQnfields(res);
		cout << endl << "number of rows = " << nrows << " , fields returned = " << nfields;
		for (r = 0; r < nrows; r++)
		for (n = 0; n < nfields; n++)
			cout << endl << PQgetvalue(res,r,n);
	    }
	}
	PQclear(res);
	
	res = PQexec(conn, "commit");
	cout << endl << "********Status is : " << PQresStatus(PQresultStatus(res));
	cout << endl << "********Result message : "<< PQresultErrorMessage(res);
	PQclear(res);
    }

    PQfinish(conn);

    pthread_exit(NULL);
}

int main()
{
    int rc;

    int *taskids[NUM_THREADS];
    
    pthread_t  *pThread = new pthread_t[ NUM_THREADS ];
    
    for(int t=0; t<NUM_THREADS; t++)
    {
	taskids[t] = (int *) malloc(sizeof(int));
   	*taskids[t] = t;

	rc = pthread_create(&pThread[t], NULL, connect, (void *) taskids[t]);
	if (rc)
	{
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
      	}
    }
    for ( int j = 0; j < NUM_THREADS ;j++ )
	pthread_join(pThread[j],0);		
		
    printf("All threads completed successfully \n");			
	delete []pThread;

    for(int t=0; t<NUM_THREADS; t++)
    {
	delete taskids[t];
    }
    pthread_exit(NULL);
}


