/* -*- mode: c; indent-tabs-mode: nil; c-file-style: "stroustrup"; -*- */
/*
 * gcc -W -Wall -Wextra -pedantic -o pg-test-bytea-free pg-test-bytea-free.c -lpq
 *
 * create table files(id int, data bytea);
 * insert into files values (60, repeat('1234567890', (60 * 1024 * 1024) / 10)::bytea); 
 * insert into files values (300, repeat('1234567890', (300 * 1024 * 1024) / 10)::bytea);
 * insert into files values (100, repeat('1234567890', (100 * 1024 * 1024) / 10)::bytea);
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>
#include <internal/libpq-int.h>

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

void test_for(PGconn *conn, int pk)
{
    PGresult *res;
    char query[128];
    int i;

    sprintf(query, "SELECT data FROM files WHERE id = %d", pk);
    printf("=== %d ===\n", pk);
    for (i = 0 ; i < 3; ++i)
    {
        res = PQexec(conn, query);
        if (PQresultStatus(res) != PGRES_TUPLES_OK)
        {
            fprintf(stderr, "%s failed: %s", query, PQerrorMessage(conn));
            PQclear(res);
            exit_nicely(conn);
        }

        printf("%dMb BEFORE PQclear\n", pk);
        system("ps axv | grep [pg]-test-bytea");

        PQclear(res);

        printf("%dMb AFTER PQclear\n", pk);
        system("ps axv | grep [pg]-test-bytea");

        printf("*** inBuffer %p inBufSize %10d inStart %10d inCursor %10d inEnd %10d\n",
               conn->inBuffer, conn->inBufSize, conn->inStart, conn->inCursor, conn->inEnd);

        puts("");
    }
}

int main ()
{
    PGconn *conn;

    conn = PQconnectdb("");
    if (PQstatus(conn) != CONNECTION_OK)
    {
        fprintf(stderr, "Connection to database failed: %s",
                PQerrorMessage(conn));
        exit_nicely(conn);
    }

    puts("BEFORE PQexec loop");
    system("ps axv | grep [pg]-test-bytea");

    test_for(conn, 300);
    test_for(conn, 100);
    test_for(conn, 60);

    return 0;
}
