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

/* SQLRelay headers */
#ifdef WIN32
#define RUDIMENTS_HAVE_CHAR16_T // hack to solve some rudiments vs VS2019 problem
#endif
#include <sqlrelay/sqlrclient.h>

#define F2_MAX_LEN 50
#define MAX_REC 100

typedef const char *(*ss2s)(const char *s1, const char *s2);
typedef const char *(*sss2s)(const char *s1, const char *s2, const char *s3);

// 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;
    }
}

class OOSQLR : public DB
{
private:
    sqlrconnection *con;
    sss2s placeholder;
    ss2s bindname;
    void ConnectionExit(sqlrconnection *con);
    void CursorExit(sqlrcursor *curs);
    void OtherExit(const char *msg);
public:
    // construct instance
    OOSQLR(const char *host, int port, const char *un, const char *pw, sss2s placeholder, ss2s bindname);
    // destruct instance
    virtual ~OOSQLR();
    // 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 OOSQLR::ConnectionExit(sqlrconnection *con)
{
    cout << "SQLR connection error: " << con->errorMessage() << endl;
    exit(1);
}

void OOSQLR::CursorExit(sqlrcursor *curs)
{
    cout << "SQLR cursor error: " << curs->errorMessage() << endl;
    exit(1);
}

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

// construct instance
OOSQLR::OOSQLR(const char *host, int port, const char *un, const char *pw, sss2s placeholder, ss2s bindname)
{
    con = new sqlrconnection(host, port, NULL, un, pw, 0, 1);
    con->autoCommitOn();
    this->placeholder = placeholder;
    this->bindname = bindname;
}

// destruct instance
OOSQLR::~OOSQLR()
{
    delete con;
}

// get f1 given f2
int OOSQLR::T1GetOne(const char *f2)
{
    // get cursor
    sqlrcursor *curs = new sqlrcursor(con);
    // prepare
    char sqlstr[40 + 2 * F2_MAX_LEN];
    sprintf(sqlstr, "SELECT f1 FROM t1 WHERE f2 = %s", placeholder("1", "f2", "text"));
    curs->prepareQuery(sqlstr);
    // bind parameters
    curs->inputBind(bindname("1", "f2"), f2);
    // execute
    int stat = curs->executeQuery();
    if(!stat) CursorExit(curs);
    // process result
    if(curs->getField((uint64_t)0, (uint32_t)0) == NULL)
    {
        OtherExit("Row not found");
        return 0; /* will never be reached */
    }
    int f1 = curs->getFieldAsInteger((uint64_t)0, (uint32_t)0);
    con->endSession();
    // close cursor 
    delete curs;
    return f1;
}

// get all records
int OOSQLR::T1GetAll(struct t1 *buf, int bufsiz)
{
    // get cursor
    sqlrcursor *curs = new sqlrcursor(con);
    // execute
    int stat = curs->sendQuery("SELECT f1,f2 FROM t1");
    if(!stat) CursorExit(curs);
    // process result
    curs->setResultSetBufferSize(100);
    int row = 0;
    int count = 0;
    for(;;)
    {
        if(count >= bufsiz) break;
        if(curs->getField((uint64_t)row, (uint32_t)0) == NULL) break;
        buf[count].f1 = curs->getFieldAsInteger((uint64_t)row, (uint32_t)0);
        strcpy(buf[count].f2, curs->getField((uint64_t)row, (uint32_t)1));
        count++;
        row++;
    }
    con->endSession();
    // close cursor
    delete curs;
    return count;
}

// add record
void OOSQLR::T1Put(int f1, const char *f2)
{
    // get cursor
    sqlrcursor *curs = new sqlrcursor(con);
    // prepare
    char sqlstr[40 + 2 * F2_MAX_LEN];
    sprintf(sqlstr, "INSERT INTO t1 VALUES(%s, %s)", placeholder("1", "f1", "int"), placeholder("2", "f2", "text"));
    curs->prepareQuery(sqlstr);
    // bind parameters
    curs->inputBind(bindname("1", "f1"), f1);
    curs->inputBind(bindname("2", "f2"), f2);
    // execute
    int stat = curs->executeQuery();
    if(!stat) CursorExit(curs);
    int n = curs->affectedRows();
    if(n != 1)
    {
        OtherExit("INSERT did not insert 1 row");
    }
    con->endSession();
    // close cursor 
    delete curs;
}

// delete record
void OOSQLR::T1Remove(int f1)
{
    // get cursor
    sqlrcursor *curs = new sqlrcursor(con);
    // prepare
    char sqlstr[40 + 2 * F2_MAX_LEN];
    sprintf(sqlstr, "DELETE FROM t1 WHERE f1 = %s", placeholder("1", "f1", "int"));
    curs->prepareQuery(sqlstr);
    // bind parameters
    curs->inputBind(bindname("1", "f1"), f1);
    // execute
    int stat = curs->executeQuery();
    if(!stat) CursorExit(curs);
    int n = curs->affectedRows();
    if(n != 1)
    {
        OtherExit("DELETE did not delete 1 row");
    }
    con->endSession();
    // close cursor
    delete curs;
}

void test(const char *host, int port, const char *un, const char *pw, sss2s placeholder, ss2s bindname)
{
    cout << "Connect host=" << host << " port=" << port << endl; 
    /* open */
    DB *db = new OOSQLR(host, port, un, pw, placeholder, bindname);
    /* test T1GetOne */
    int f1 = db->T1GetOne("BB");
    printf("%d\n", f1);
    /* test T1GetAll */
    db->T1Dump();
    /* test T1Put */
    db->T1Put(999, "XXX");
    db->T1Dump();
    /* test T1Remove */
    db->T1Remove(999);
    db->T1Dump();
}

#define MAXIX 100

static int phix = 0;
static char phbuf[MAXIX][16];
static int bnix = 0;
static char bnbuf[MAXIX][16];

/* standard (ODBC, DB2, MySQL) */
static const char *std_ph(const char *num, const char *nam, const char *typ)
{
    return "?";
}

static const char *std_bn(const char *num, const char *nam)
{
    return num;
}

/* PostgreSQL */
static const char *pgsql_ph(const char *num, const char *nam, const char *typ)
{
    char *buf = phbuf[phix];
    sprintf(buf, "$%s::%s", num, typ);
    phix = (phix + 1) % MAXIX;
    return buf;
}

static const char *pgsql_bn(const char *num, const char *nam)
{
    return num;
}

/* Oracle */
static const char *ora_ph(const char *num, const char *nam, const char *typ)
{
    char *buf = phbuf[phix];
    sprintf(buf, ":%s", nam);
    phix = (phix + 1) % MAXIX;
    return buf;
}

static const char *ora_bn(const char *num, const char *nam)
{
    return nam;
}

int main()
{
    test("arnepc4", 9001, "arne", "topsecret", std_ph, std_bn); /* 9001 = localmysql */
    test("arnepc4", 9002, "arne", "topsecret", pgsql_ph, pgsql_bn); /* 9002 = localpgsql */
    test("arnepc4", 9003, "arne", "topsecret", std_ph, std_bn); /* 9003 = localdb2 */
    test("arnepc4", 9004, "arne", "topsecret", ora_ph, ora_bn); /* 9004 = localora */
    test("arnepc4", 9005, "arne", "topsecret", std_ph, std_bn); /* 9005 = odbcsqlsrv */
    test("arnepc4", 9006, "arne", "topsecret", std_ph, std_bn); /* 9006 = odbcmysql */
    test("arnepc4", 9007, "arne", "topsecret", std_ph, std_bn); /* 9007 = odbcpgsql */
    test("arnepc4", 9008, "arne", "topsecret", std_ph, std_bn); /* 9008 = odbcdb2 */
    //test("arnepc4", 9009, "arne", "topsecret", std_ph, std_bn); /* 9009 = odbcora */ /* NOTE: not working - INSERT and UPDATE fail */
    test("arnepc4", 9010, "arne", "topsecret", std_ph, std_bn); /* 9010 = vmsmysql */
    test("arnepc4", 9011, "arne", "topsecret", std_ph, std_bn); /* 9011 = vmsodbcrdb */
    //test("arnepc4", 9012, "arne", "topsecret", std_ph, std_bn); /* 9012 = vmsodbcmysql */ /* NOTE: not working - hanging */
    test("arnepc4", 9013, "arne", "topsecret", std_ph, std_bn); /* 9013 = vmsodbcmimer */
    return 0;
}
