/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
/* standard C headers */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* OS specific headers */
#ifdef _WIN32
#include <winsock.h>
#endif
#ifdef _unix
#include <arpa/inet.h>
#endif

/* PgSQL headers */
#include <libpq-fe.h>

#define F2_MAX_LEN 50
#define MAX_REC 100

/* table structure */
struct t1
{
    int f1;
    char f2[F2_MAX_LEN + 1];
};

/* error handling functions */
void con_exit(PGconn *con)
{
    printf("PostgreSQL error: %s\n", PQerrorMessage(con));
    exit(1);
}

void res_exit(PGresult *res)
{
    printf("PostgreSQL error: %s\n", PQresultErrorMessage(res));
    exit(1);
}

void other_exit(char *msg)
{
    printf("%s\n", msg);
    exit(1);
}

/* get connection */
PGconn *get_connection(const char *constr)
{
    PGconn *con;
    con = PQconnectdb(constr);
    if (PQstatus(con) != CONNECTION_OK) con_exit(con);
    return con;
}

#define TXTFMT  0
#define BINFMT 1

/* get f1 given f2 */
int t1_get_one(PGconn *con, char *f2)
{
    PGresult *res;
    char *sqlstr;
    int f1;
    const char *paramval[1];
    int paramlen[1];
    int paramfmt[1];
    /* prepare */
    sqlstr = "SELECT f1 FROM t1 WHERE f2 = $1::text";
    res = PQprepare(con, "stmt_get_one", sqlstr, 0, NULL);
    if (PQresultStatus(res) != PGRES_COMMAND_OK) res_exit(res);
    PQclear(res);
    /* execute and process result */
    paramval[0] = f2;
    paramlen[0] = strlen(f2);
    paramfmt[0] = BINFMT;
    res = PQexecPrepared(con, "stmt_get_one", 1, paramval, paramlen, paramfmt, BINFMT);
    if(PQresultStatus(res) != PGRES_TUPLES_OK) res_exit(res);
    if(PQntuples(res) > 0)
    {
        f1 = ntohl(*((int *)PQgetvalue(res, 0, 0)));
        PQclear(res);
        PQexec(con, "DEALLOCATE stmt_get_one");
        return f1;
    }
    else
    {
        other_exit("Row not found");
        return 0; /* will never be reached */
    }
}

/* get all records */
int t1_get_all(PGconn *con, struct t1 *buf, int bufsiz)
{
    PGresult *res;
    char *sqlstr;
    int count, i;
    /* prepare */
    sqlstr = "SELECT f1,f2 FROM t1";
    res = PQprepare(con, "stmt_get_all", sqlstr, 0, NULL);
    if (PQresultStatus(res) != PGRES_COMMAND_OK) res_exit(res);
    PQclear(res);
    /* execute and process result */
    res = PQexecPrepared(con, "stmt_get_all", 0, NULL, NULL, NULL, BINFMT);
    if(PQresultStatus(res) != PGRES_TUPLES_OK) res_exit(res);
    count = PQntuples(res);
    for(i = 0; i < count && i < bufsiz; i++)
    {
        buf[i].f1 = ntohl(*((int *)PQgetvalue(res, i, 0)));
        strcpy(buf[i].f2, PQgetvalue(res, i, 1));
    }
    PQclear(res);
    PQexec(con, "DEALLOCATE stmt_get_all");
    /* */
    return count;
}

/* add record */
void t1_put(PGconn *con, int f1, char *f2)
{
    PGresult *res;
    char *sqlstr;
    const char *paramval[2];
    int paramlen[2];
    int paramfmt[2];
    int temp;
    /* prepare */
    sqlstr = "INSERT INTO t1 VALUES($1::int, $2::text)";
    res = PQprepare(con, "stmt_put", sqlstr, 0, NULL);
    if (PQresultStatus(res) != PGRES_COMMAND_OK) res_exit(res);
    PQclear(res);
    /* execute and check if OK */
    temp = htonl(f1);
    paramval[0] = (char *)&temp;
    paramlen[0] = sizeof(temp);
    paramfmt[0] = BINFMT;
    paramval[1] = f2;
    paramlen[1] = strlen(f2);
    paramfmt[1] = BINFMT;
    res = PQexecPrepared(con, "stmt_put", 2, paramval, paramlen, paramfmt, 0);
    if(PQresultStatus(res) != PGRES_COMMAND_OK) res_exit(res);
    if(strcmp(PQcmdTuples(res), "1") != 0)
    {
        other_exit("INSERT did not insert 1 row");
    }
    PQclear(res);
    PQexec(con, "DEALLOCATE stmt_put");
}

/* delete record */
void t1_remove(PGconn *con, int f1)
{
    PGresult *res;
    char *sqlstr;
    const char *paramval[2];
    int paramlen[2];
    int paramfmt[2];
    int temp;
    /* prepare */
    sqlstr = "DELETE FROM t1 WHERE f1 = $1::int";
    res = PQprepare(con, "stmt_remove", sqlstr, 0, NULL);
    if (PQresultStatus(res) != PGRES_COMMAND_OK) res_exit(res);
    PQclear(res);
    /* execute and check if OK */
    temp = htonl(f1);
    paramval[0] = (char *)&temp;
    paramlen[0] = sizeof(temp);
    paramfmt[0] = BINFMT;
    res = PQexecPrepared(con, "stmt_remove", 1, paramval, paramlen, paramfmt, 0);
    if(PQresultStatus(res) != PGRES_COMMAND_OK) res_exit(res);
    if(strcmp(PQcmdTuples(res), "1") != 0)
    {
        other_exit("DELETE did not delete 1 row");
    }
    PQclear(res);
    PQexec(con, "DEALLOCATE stmt_remove");
}

/* print all records */
void t1_dump(PGconn *con)
{
    struct t1 buf[MAX_REC];
    int i, n;
    n = t1_get_all(con, buf, MAX_REC);
    for(i = 0; i < n; i++)
    {
        printf("%d \"%s\"\n", buf[i].f1, buf[i].f2);
    }
}

int main()
{
    PGconn *con;
    int f1;
    /* get connection */
    con = get_connection("host=localhost port=5432 dbname=Test user=postgres password=xxxxxx");
    /* test t1_get_one */
    f1 = t1_get_one(con, "BB");
    printf("%d\n", f1);
    /* test t1_get_all */
    t1_dump(con);
    /* test t1_put */
    t1_put(con, 999, "XXX");
    t1_dump(con);
    /* test t1_remove */
    t1_remove(con, 999);
    t1_dump(con);
    /* close connection */
    PQfinish(con);
    return 0;
}
