// 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 <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;


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

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

static const int F2_MAX_LEN = 50;
static const int MAX_REC = 100;

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

class DB
{
public:
    // destruct instance
    virtual ~DB() { };
    // get f1 given f2
    virtual int T1GetOne(const char *f2) = 0;
    // get all records
    virtual int T1GetAll(struct t1 *buf, int bufsiz) = 0;
    // add record
    virtual void T1Put(int f1, const char *f2) = 0;
    // delete record
    virtual void T1Remove(int f1) = 0;
    // print all records
    void T1Dump();
};

// print all records
void DB::T1Dump()
{
    struct t1 buf[MAX_REC];
    int i, n;
    n = T1GetAll(buf, MAX_REC);
    for(i = 0; i < n; i++)
    {
        cout << buf[i].f1 << " " << buf[i].f2 << endl;
    }
}

const int TXTFMT = 0;
const int BINFMT = 1;

class Pgsql : public DB
{
private:
    PGconn *con;
    void ConExit();
    void ResExit(PGresult *res);
    void OtherExit(const char *msg);
public:
    // construct instance
    Pgsql(const char *constr);
    // destruct instance
    virtual ~Pgsql();
    // get f1 given f2
    virtual int T1GetOne(const char *f2);
    // get all records
    virtual int T1GetAll(struct t1 *buf, int bufsiz);
    // add record
    virtual void T1Put(int f1, const char *f2);
    // delete record
    virtual void T1Remove(int f1);
};

// error handling functions
void Pgsql::ConExit()
{
    cout << "PostgreSQL error: " <<  PQerrorMessage(con) << endl;;
    exit(1);
}

void Pgsql::ResExit(PGresult *res)
{
    cout << "PostgreSQL error: " << PQresultErrorMessage(res) << endl;
    exit(1);
}

void Pgsql::OtherExit(const char *msg)
{
    cout << msg << endl;
    exit(1);
}

// construct instance
Pgsql::Pgsql(const char *constr)
{
    con = PQconnectdb(constr);
    if (PQstatus(con) != CONNECTION_OK) ConExit();
}

// destruct instance
Pgsql::~Pgsql()
{
    PQfinish(con);
}

// get f1 given f2
int Pgsql::T1GetOne(const char *f2)
{
    PGresult *res;
    const 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) ResExit(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) ResExit(res);
    if(PQntuples(res) > 0)
    {
        f1 = ntohl(*((int *)PQgetvalue(res, 0, 0)));
        PQclear(res);
        PQexec(con, "DEALLOCATE stmt_get_one");
        return f1;
    }
    else
    {
        OtherExit("Row not found");
        return 0; /* will never be reached */
    }
}

// get all records
int Pgsql::T1GetAll(struct t1 *buf, int bufsiz)
{
    PGresult *res;
    const 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) ResExit(res);
    PQclear(res);
    /* execute and process result */
    res = PQexecPrepared(con, "stmt_get_all", 0, NULL, NULL, NULL, BINFMT);
    if(PQresultStatus(res) != PGRES_TUPLES_OK) ResExit(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 Pgsql::T1Put(int f1, const char *f2)
{
    PGresult *res;
    const 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) ResExit(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) ResExit(res);
    if(strcmp(PQcmdTuples(res), "1") != 0)
    {
        OtherExit("INSERT did not insert 1 row");
    }
    PQclear(res);
    PQexec(con, "DEALLOCATE stmt_put");
}

// delete record
void Pgsql::T1Remove(int f1)
{
    PGresult *res;
    const 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) ResExit(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) ResExit(res);
    if(strcmp(PQcmdTuples(res), "1") != 0)
    {
        OtherExit("DELETE did not delete 1 row");
    }
    PQclear(res);
    PQexec(con, "DEALLOCATE stmt_remove");
}

int main()
{
    // get database connection
    DB *db = new Pgsql("host=localhost port=5432 dbname=Test user=postgres password=xxxxxx");
    // test T1GetOne
    int f1 = db->T1GetOne("BB");
    cout << f1 << endl;
    // test T1GetAll
    db->T1Dump();
    // test t1_put
    db->T1Put(999, "XXX");
    db->T1Dump();
    // test t1_remove
    db->T1Remove(999);
    db->T1Dump();
    // release database connection
    delete db;
    return 0;
}
