/*
 * Testing of new asynchronous portal interface.
 * 
 * Do the following at the monitor:
 *

 create test1 (i = int4) \g
 create test1a (i = int4) \g

 define rule r1 is on append to test1 do
    [append test1a (i = new.i)
    notify test1a]

 \g
 * Then start up this process.

 append test1 (i = 10) \g

 * The value i=10 should be printed by this process.
 */

#include "tmp/simplelists.h"
#include "tmp/libpq.h"

void main()
{
    extern int PQAsyncNotifyWaiting;
    PQNotifyList *l;
    PortalBuffer *portalbuf;
    char *res;
    int ngroups,tupno, grpno, ntups, nflds;
    PQsetdb(getenv("USER"));

    PQexec("listen test1a");

    while(1) {
	sleep(1);
	if (PQAsyncNotifyWaiting) {
	    PQexec(" ");
	    l = PQnotifies();
	    if (l != NULL) {
		printf("notification on relation %s\n",l->relname);
		res = PQexec("retrieve (test1a.i)");
		if (*res == 'E') {
		    fprintf(stderr,"%s\nfailed",++res);
		    goto exit_error;
		}
		if (*res != 'P') {
		    fprintf(stderr,"%s\nno portal",++res);
		}
		/* get tuples in relation */
		portalbuf = PQparray(++res);
		ngroups = PQngroups(portalbuf);
		for (grpno = 0; grpno < ngroups; grpno++) {
		    ntups = PQntuplesGroup(portalbuf, grpno);
		    if ((nflds = PQnfieldsGroup(portalbuf, grpno)) != 1) {
			fprintf(stderr, "expected 1 attributes, got %d\n", nflds);
			goto exit_error;
		    }
		    for (tupno = 0; tupno < ntups; tupno++) {
			printf ("got i=%s\n",PQgetvalue(portalbuf,tupno,0));
		    }
		}
		break;
	    }
	}
    }

    PQfinish();
    exit(0);
  exit_error:
    PQfinish();
    exit(1);

}
