testlibpq2.c 2.5 KB
Newer Older
1 2
/*
 * testlibpq2.c
3
 *		Test of the asynchronous notification interface
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
   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];

 * Then start up this program
 * After the program has begun, do

INSERT INTO TBL1 values (10);

 *
 *
 */
#include <stdio.h>
22
#include <stdlib.h>
23 24
#include "libpq-fe.h"

25
static void
26
exit_nicely(PGconn *conn)
27
{
28 29
	PQfinish(conn);
	exit(1);
30 31
}

32
int
33 34
main()
{
35 36 37 38 39
	char	   *pghost,
			   *pgport,
			   *pgoptions,
			   *pgtty;
	char	   *dbName;
40 41 42

	/*
	 * int			nFields; int		  i, j;
43
	 */
44 45 46 47

	PGconn	   *conn;
	PGresult   *res;
	PGnotify   *notify;
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

	/*
	 * begin, by setting the parameters for a backend connection if the
	 * parameters are null, then the system will try to use reasonable
	 * defaults by looking up environment variables or, failing that,
	 * using hardwired constants
	 */
	pghost = NULL;				/* host name of the backend server */
	pgport = NULL;				/* port of the backend server */
	pgoptions = NULL;			/* special options to start up the backend
								 * server */
	pgtty = NULL;				/* debugging tty for the backend server */
	dbName = getenv("USER");	/* change this to the name of your test
								 * database */

	/* make a connection to the database */
	conn = PQsetdb(pghost, pgport, pgoptions, pgtty, dbName);

	/* check to see that the backend connection was successfully made */
	if (PQstatus(conn) == CONNECTION_BAD)
	{
		fprintf(stderr, "Connection to database '%s' failed.\n", dbName);
		fprintf(stderr, "%s", PQerrorMessage(conn));
		exit_nicely(conn);
	}

	res = PQexec(conn, "LISTEN TBL2");
	if (PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "LISTEN command failed\n");
		PQclear(res);
		exit_nicely(conn);
	}

	/*
	 * should PQclear PGresult whenever it is no longer needed to avoid
	 * memory leaks
	 */
	PQclear(res);

	while (1)
	{
		/* async notification only come back as a result of a query */
		/* we can send empty queries */
		res = PQexec(conn, " ");
93
/*		printf("res->status = %s\n", PQresStatus(PQresultStatus(res))); */
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
		/* check for asynchronous returns */
		notify = PQnotifies(conn);
		if (notify)
		{
			fprintf(stderr,
				 "ASYNC NOTIFY of '%s' from backend pid '%d' received\n",
					notify->relname, notify->be_pid);
			free(notify);
			break;
		}
		PQclear(res);
	}

	/* close the connection to the database and cleanup */
	PQfinish(conn);
109 110
	return 0;					/* Though PQfinish(conn1) has called
								 * exit(1) */
111
}