#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "db.h"

static int
scalar(PGconn *pg, const char *sql, int n, const char *const *params)
{
	PGresult *res = db_q(pg, sql, n, params);
	int value;

	assert(res != NULL && PQntuples(res) == 1);
	value = atoi(PQgetvalue(res, 0, 0));
	PQclear(res);
	return value;
}

int
main(int argc, char **argv)
{
	struct conf cf;
	PGconn *pg;
	PGresult *res;
	const char *params[3];
	char *large;
	int pid;

	assert(argc == 2 && conf_load(&cf, argv[1]) == 0);
	pg = db_get(&cf);
	assert(pg != NULL);
	pid = PQbackendPID(pg);
	assert(scalar(pg, "SELECT 1", 0, NULL) == 1);
	db_request_done();
	pg = db_get(&cf);
	assert(PQbackendPID(pg) == pid);

	assert(db_do(pg, "BEGIN", 0, NULL) == 0);
	res = db_q(pg, "SELECT repeat('x', 524288)", 0, NULL);
	assert(res != NULL && PQgetlength(res, 0, 0) == 524288);
	PQclear(res);
	assert(PQtransactionStatus(pg) == PQTRANS_INTRANS);
	assert(PQbackendPID(pg) == pid);
	assert(db_do(pg, "COMMIT", 0, NULL) == 0);
	db_request_done();
	pg = db_get(&cf);
	assert(PQbackendPID(pg) != pid);
	pid = PQbackendPID(pg);

	large = malloc(524289);
	assert(large != NULL);
	memset(large, 'x', 524288);
	large[524288] = '\0';
	params[0] = large;
	assert(scalar(pg, "SELECT length($1::text)", 1, params) == 524288);
	db_request_done();
	pg = db_get(&cf);
	assert(PQbackendPID(pg) != pid);
	pid = PQbackendPID(pg);

	large[204800] = '\0';
	params[1] = NULL;
	params[2] = large;
	assert(scalar(pg, "SELECT length($1::text) + COALESCE(length($2::text), 0) + length($3::text)",
	    3, params) == 409600);
	db_request_done();
	pg = db_get(&cf);
	assert(PQbackendPID(pg) != pid);
	pid = PQbackendPID(pg);

	large[204800] = 'x';
	assert(db_q(pg, "SELECT 1/0 WHERE $1::text IS NOT NULL", 1, params) == NULL);
	db_request_done();
	pg = db_get(&cf);
	assert(PQbackendPID(pg) != pid);
	res = db_q(pg, "SELECT repeat('x', 524288)", 0, NULL);
	assert(res != NULL);
	PQclear(res);
	db_request_done();
	free(large);
	puts("database cache: small connection reuse, large results/params/errors recycled only at API boundary");
	return 0;
}
