#include <iostream>
#include "libpq-fe.h"

/* Compiled with:  g++ -Wall -I /usr/include/postgresql/ t.cpp -lpq -lpthread */

using namespace std;

#define QUERY_STRING "select * from bigtable ;"
#define CONNECT_STRING "dbname=kleptog  user=kleptog"

void *
queryDB(void *p)
{

    cout << "I Am in Routine Function *** " << endl;
    PGconn *_conn;
    PGresult *_res;
    char *dbn, *usn;
    cout << "i am connecting:" << endl;
    _conn = PQconnectdb(CONNECT_STRING);
    if(PQstatus(_conn) == CONNECTION_OK)
        cout << "connection is ready" << endl;
    dbn = PQdb(_conn);
    usn = PQuser(_conn);
    if(PQstatus(_conn) == CONNECTION_BAD)
        cout << "the connection is not hapened" << endl;
    string string1, string2, string3;
    _res = PQexec(_conn, QUERY_STRING);
    if(!(PQresultStatus(_res) == PGRES_COMMAND_OK || PQresultStatus(_res) == PGRES_TUPLES_OK))
    {
        /*If this Function is *NOT* called from main thread then we will end up by entering here. */
        string msg = PQresultErrorMessage(_res);
        PQclear(_res);
        cout << "Query Execution is Not OK **********" << msg << endl;
    }
    else
    {
        /*If this Function is  called from main thread then we will end up by entering here. */
        int no_of_tuples, no_of_columns;
        string stg;
        no_of_columns = PQnfields(_res);
        no_of_tuples = PQntuples(_res);

        cout << "no of tuples  " << no_of_tuples << endl;
        cout << "Number Of Columns " << no_of_columns << endl;
#if 0
        char *str1;
        for (int u = 0; u < no_of_tuples; u++)
        {
            for (int y = 0; y < no_of_columns; y++)
            {
                str1 = PQgetvalue(_res, u, y);
                cout << "*************Printing *** " << u << "th Row " << y <<
                    "th Column****************" << endl;
                cout << str1 << endl;
            }
            cout << endl;
        }
#endif
        PQclear(_res);
    }
    PQfinish(_conn);
    return NULL;
}

#define STACK_SIZE (512 * 1024 * 2)
//#define STACK_SIZE (512 * 1024 * 2 * 20)

int
main()
{
    //calling queryDB from other thread ..DOESN'T Work here
    size_t _stackSize(STACK_SIZE);
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setstacksize( &attr, _stackSize) ;
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    pthread_t thread_t;
    pthread_create(&thread_t, &attr, queryDB, NULL);
    int rc, status;
    rc = pthread_join(thread_t, (void **)&status);

    //calling queryDB from main thread WORKS here..

    queryDB(NULL);
    return 1;
}
