#include <postgresql/libpq-fe.h>
#include <stdio.h>

// gcc -lpq -o test test.c

static const char *conninfo = "host=xxx.xxx.xx.xx port=5432 dbname=xxx user=xxx password=xxx connect_timeout=30";
// static const char *conninfo = "host=db.xxx.de port=5432 dbname=xxx user=xxx password=xxx connect_timeout=30";

static int fetch_from_database(void)
{
	PGconn *conn;
	PGresult *res;
	char sql[32768];
	int c_username, c_ip;
	int ret = -1;
	unsigned int max, i;

	conn = PQconnectdb(conninfo);
	printf("called PQconnectdb: %p\n", conn);
	if (!conn) {
		printf("connection failed\n");
		goto out_finish;
	}

	snprintf(sql, sizeof(sql), "SELECT username,ip FROM extras WHERE server=(SELECT id FROM servers WHERE IP='xxx.xxx.xx.xx') ORDER BY username");
	res = PQexec(conn, sql);
	printf("called PQexec: %p\n", res);
	if (PQresultStatus(res) != PGRES_TUPLES_OK) {
		printf("couldn't get data\n");
		goto out;
	}

	max = (unsigned int)PQntuples(res);
	if (max == 0) { 
		ret = 0;
		goto out;
	}

	if (max > 64) {
		printf("too many results\n");
		goto out;
	}

	c_username = PQfnumber(res, "username");
	c_ip = PQfnumber(res, "ip");

	if (c_username == -1 || c_ip == -1) {
		printf("weird table structure found\n");
		goto out;
	}

	for (i = 0; i < max; i++) {
		(void)PQgetvalue(res, i, c_username);
		(void)PQgetvalue(res, i, c_ip);
	}

	ret = 0;
out:
	printf("calling PQclear: %p\n", res);
	PQclear(res);
out_finish:
	printf("calling PQfinish: %p\n", conn);
	PQfinish(conn);
	res = NULL;
	conn = NULL;

	return ret;
}

int main(void)
{
	while(fetch_from_database() == 0);
	return 0;
}
