// testlibpq2.cpp
//  Test of the asynchronous notification interface
//
// Note: Of course, you have to create the data base.
//       $ createdb <login name>
//
//
// Start this program, then from psql (psql <login name>)
// in another window do:
//   NOTIFY TBL2;
//
// Or, if you want to get fancy, try this:
// Populate a database with the following:
//
//   CREATE TABLE TBL1 (i int4);
//
//   CREATE TABLE TBL2 (i int4);
//
//   CREATE RULE r1 AS ON INSERT TO TBL1 DO
//     (INSERT INTO TBL2 values (new.i); NOTIFY TBL2);
//
// and do
//
//   INSERT INTO TBL1 values (10);


#define _GNU_SOURCE
#include <stdio.h>

#include <stdlib.h>

#include <libpq++.h>

#include <unistd.h>


int main(int argc, char* argv[])
{
  char *username = NULL;
  char *passwd   = "";
  char *dbname   = ""; // "shop";
  char *dbhost   = "localhost";
  int   dbport   = 0;
  
  char *dbstring; 
  char *tmp = "";
  if (dbport)
    asprintf(&tmp, " port=%d", dbport);
  //asprintf (&dbstring, "dbname=%s password=%s%s%s%s%s%s",
  asprintf (&dbstring, "password=%s%s%s%s%s%s",
	    dbname, passwd, (dbhost?" host=":""), 
	    (dbhost?dbhost:""), (username?" user=":""),
	    (username?username:""), tmp);
  if (dbport)
    free(tmp);

  PgDatabase* db;
  db = new PgDatabase(dbstring);
  if (db->Status() == CONNECTION_BAD)
    {
      printf("Can't log in to the data base: %s",
	     db->ErrorMessage());
      delete db;
      exit(0);
    }
  printf("Connected to the data base: %s \n", dbname );

  asprintf(&tmp, "LISTEN TBL2");
  if (!db->ExecCommandOk(tmp))
    {
      free(tmp);
      printf("The '%s' command has failed: %s",
	     tmp, db->ErrorMessage());
      exit(0);
    }
  free(tmp);
  printf("Listening products: %s \n", dbname );

  while (1)
    {
      sleep(1);
      
      if ( db->Notifies() != NULL)
	{
	  printf("Notify \n");
	  fflush(NULL);
	}
      else
	{
	  printf(".");
	  fflush(NULL);
	}
    }
}
