/*
 * fe-time.c
 *
 * Connects to database postgres and expects some pgbench database to be there.
 *
 * To create/populate one, 100,000 is adviced. Try eg.:
 * 
 *   pgbench -i -s 1
 *
 * Compile with:
 *
 *   gcc -lpq -I /pg/includes/path -o fe-time fe-time.c
 * 
 * Run with:
 *
 *   time ./fe-time
 *
 * The optional parameter is the time to wait in ms between every batch of
 * 1000 rows:
 *
 *   time ./fe-time 100
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include "libpq-fe.h"

#define DEFAULT_SLEEP 100000000

static void
exit_nicely(PGconn *conn, int rc)
{
	/* close & cleanup */
	fprintf(stderr, "\n");
	PQfinish(conn);
	exit(rc);
}

int
main(int argc, char **argv)
{
	PGconn        *conn;
	PGresult      *res;
	int            status, i = 0;
	struct timespec delay = {0, DEFAULT_SLEEP};

	errno = 0;

	if (argc > 1) {
		long nano = strtol(argv[1], NULL, 10);
		if (errno == 0) delay.tv_nsec = nano*1000000;
	}

	fprintf(stderr, "delay set to %dms per thousands\n", delay.tv_nsec/1000000);

	conn = PQconnectdb("");

	/* async query a large table */
	status = PQsendQuery(conn, "SELECT * FROM pgbench_accounts");
	if (status != 1)
	{
		fprintf(stderr, "Async query failed: %s", PQerrorMessage(conn));
		exit_nicely(conn, 1);
	}

	/* set single row mode */
	status = PQsetSingleRowMode(conn);
	if (status != 1)
	{
		fprintf(stderr, "PQsetSingleRowMode failed: %s", PQerrorMessage(conn));
		exit_nicely(conn, 1);
	}

	/* get result one row at a time and sleep every 1000 rows */
	while (res = PQgetResult(conn)) {
		if (res == NULL) break; /* query ended */
		i++;

		if (PQresultStatus(res) == PGRES_SINGLE_TUPLE
			&& i%1000 == 0)
		{
			/* fake some heavy work */
			nanosleep((const struct timespec *)&delay, NULL);
			fprintf(stderr, "processed %d rows               \r", i);
		}

		PQclear(res);
	}

	exit_nicely(conn, 0);

	return 0;
}
