#include <stdio.h>
#include <libpq-fe.h>
#include <iostream>
using namespace std;

void exit_nicely ( PGconn* conn ) {
    PQfinish(conn);
    exit(1);
}

#define PGHOST NULL


main() {
    // connect 
    PGconn* conn = PQsetdbLogin ( PGHOST, // host
				  NULL, // port
				  NULL, // options
				  NULL, // pgtty
				  NULL, // dbname
				  NULL, // login
				  NULL // pwd
	);
    
    if ( PQstatus(conn) == CONNECTION_BAD ) {
	cerr << "connect failed: " << PQerrorMessage(conn) << endl;
	exit_nicely(conn);
    }
    
    PGresult* res;
    if ( !(res = PQexec ( conn, "listen new_event" )) ) {
	cerr << "PQexec error: " << PQerrorMessage(conn) << endl;
	exit_nicely(conn);
    }
    PQclear ( res );
    
    if ( 0 != PQsetnonblocking ( conn, 1 ) ) {
	cerr << "pqsetnonblocking error: " << PQerrorMessage ( conn ) << endl;
	exit_nicely(conn);
    }
    
    if ( !PQexecParams ( conn, "select * from a", 0, 0, 0, 0, 0, 1 ) ) {
	cerr << "pssendquery error: " << PQerrorMessage ( conn ) << endl;
	exit_nicely(conn);
    }
    
    while ( true ) {
	if ( 0 == PQconsumeInput ( conn ) ) {
	    cerr << "PQconsumeInput error: " << PQerrorMessage(conn) << endl;
	    return 0;
	}
	
	// check notifications
	PGnotify* n;
	while ( (n = PQnotifies ( conn )) ) {
	    cerr << "got notification \"" << n->relname << "\"\n";
	    PQfreemem ( n );
	}
	
	// check if the result is ready
	if ( !PQisBusy ( conn ) ) {
	    while ( (res = PQgetResult(conn)) ) {
		cerr << "got result\n";
		PQclear ( res );
	    }
	    //break;
	}
    }
    
    // close connection
    PQfinish(conn);

    return 0;
}
