/*
 * testlibpq.c
 *
 *		Test the C version of libpq, the PostgreSQL frontend library.
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

#include "libpq-fe.h"

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

static void
do_cmd(PGconn *conn, const char *cmd)
{
	PGresult   *res;

	res = PQexec(conn, cmd);
	if (PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "%s failed: %s", cmd, PQerrorMessage(conn));
		PQclear(res);
		exit_nicely(conn);
	}
	PQclear(res);
}

static const char *
rusage_show(const struct timeval *tvold, const struct timeval *tvnew)
{
	static char result[100];
	struct timeval tv = *tvnew;

	if (tv.tv_usec < tvold->tv_usec)
	{
		tv.tv_sec--;
		tv.tv_usec += 1000000;
	}

	sprintf(result,
			 "%d.%02d sec",
			 (int) (tv.tv_sec - tvold->tv_sec),
			 (int) (tv.tv_usec - tvold->tv_usec) / 10000);

	return result;
}

int
main(int argc, char **argv)
{
	const char *conninfo;
	PGconn	   *conn;
	char		cmdbuf[1024];
	struct timeval tv;
	struct timeval tvold;
	int			i;

	/*
	 * If the user supplies a parameter on the command line, use it as the
	 * conninfo string; otherwise default to setting dbname=postgres and using
	 * environment variables or defaults for all other connection parameters.
	 */
	if (argc > 1)
		conninfo = argv[1];
	else
		conninfo = "dbname = postgres";

	/* Make a connection to the database */
	conn = PQconnectdb(conninfo);

	/* Check to see that the backend connection was successfully made */
	if (PQstatus(conn) != CONNECTION_OK)
	{
		fprintf(stderr, "Connection to database failed: %s",
				PQerrorMessage(conn));
		exit_nicely(conn);
	}

	/* Create working table */
	do_cmd(conn, "CREATE TABLE foo (f1 int, f2 int);");

	/* Start a transaction block */
	do_cmd(conn, "BEGIN");

	gettimeofday(&tvold, NULL);

	for (i = 1; i <= 250000; i++)
	{
		sprintf(cmdbuf, "INSERT INTO foo VALUES(%d,%d);", i, i);
		do_cmd(conn, cmdbuf);

		if (i % 50000 == 0)
		{
			gettimeofday(&tv, NULL);
			printf("after %d %s\n", i, rusage_show(&tvold, &tv));
			tvold = tv;
		}
	}

	/* end the transaction */
	do_cmd(conn, "END");

	/* drop table */
	do_cmd(conn, "DROP TABLE foo;");

	/* close the connection to the database and cleanup */
	PQfinish(conn);

	return 0;
}
