#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <libpq-fe.h>
#include <sys/times.h>
#include <assert.h>
#include <string.h>

// Create these items in a database named "sessionfoo"
// create table foo_sessions(session_id text, session_values text);
// create index foo_sessions_ndx on foo_sessions(session_id);

#define MAX_SESSIONS	100



char *sessions[MAX_SESSIONS];


void PQexecClear(PGconn *pg, char *sql)
{
	PGresult *pgres = PQexec(pg, sql);
	assert(pgres);
	PQclear(pgres);
}

void createRandSession(PGconn *pg, int ndx)
{
	char session[64];
	char qbuf[256];
	snprintf(session, sizeof(session), "%8X-%8X-%8X", time(0), rand(), times(NULL));
	snprintf(qbuf, sizeof(qbuf), 
		"insert into foo_sessions(session_id, session_values)values('%s','%08X')",
			session, times(NULL));
	PQexecClear(pg,qbuf);
	sessions[ndx] =  strdup(session);
}

void updateSession(PGconn *pg, int ndx)
{
	PGresult *pgres;
	char qbuf[256];
	char *session = sessions[ndx];

	snprintf(qbuf, sizeof(qbuf),
		"select * from foo_sessions where session_id = '%s'",
			session);
	PQexecClear(pg,qbuf);

	snprintf(qbuf, sizeof(qbuf),
		"update foo_sessions set session_values = '%08X' where session_id = '%s'",
			times(NULL), session);
	PQexecClear(pg,qbuf);
}



int main()
{
	int startTime;
	int loopTime;
	
	int count=0;
	int i;
	PGresult * pgres;
	PGconn *pg = PQconnectdb("dbname=sessionfoo");

	assert(pg);
	PQexecClear(pg, "delete from foo_sessions");
	PQexecClear(pg, "vacuum foo_sessions");
	
	for(i=0; i < MAX_SESSIONS; i++)
		createRandSession(pg,i);


	loopTime = time(0);
	while(loopTime == time(0)) // Wait for a fraction
		;

	startTime = loopTime = time(0);
	while(1)
	{
		int theTime = time(0);
		if(loopTime != theTime)
		{
			loopTime = theTime;
			printf("%d sessions per second, elapsed: %d\n", count, loopTime-startTime);
			count = 0;
		}
		int ndx = rand() % MAX_SESSIONS;
		updateSession(pg, ndx);
		count ++;
	}
	return 0;
}