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

// platform specific header files
#include <windows.h>

/* ODBC/CLI headers */
#ifdef DB2CLI
#include <sqlcli1.h>
#endif
#ifdef ODBC
#include <sql.h>
#include <sqlext.h>
#endif

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

class OldOdbc : public DB
{
private:
    SQLHENV env;
    SQLHDBC con;
    void EnvExit();
    void ConExit();
    void StmtExit(SQLHSTMT stmt);
    void OtherExit(const char *msg);
public:
    // construct instance
    OldOdbc(const char *dsn, const char *un, const char *pw);
    OldOdbc(const char *constr);
    // destruct instance
    virtual ~OldOdbc();
    // 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 OldOdbc::EnvExit()
{
    unsigned char state[6], buf[200];
    long int code;
    short int buflen;
    SQLError(env, SQL_NULL_HDBC, SQL_NULL_HSTMT, state, &code, buf, sizeof(buf), &buflen);
    buf[buflen] = 0;
    cout << "SQL error: " << state << " - " << code << " - " << buf << endl;
    exit(1);
}

void OldOdbc::ConExit()
{
    unsigned char state[6], buf[200];
    long int code;
    short int buflen;
    SQLError(NULL, con, SQL_NULL_HSTMT, state, &code, buf, sizeof(buf), &buflen);
    buf[buflen] = 0;
    cout << "SQL error: " << state << " - " << code << " - " << buf << endl;
    exit(1);
}

void OldOdbc::StmtExit(SQLHSTMT stmt)
{
    unsigned char state[6], buf[200];
    long int code;
    short int buflen;
    SQLError(NULL, NULL, stmt, state, &code, buf, sizeof(buf), &buflen);
    buf[buflen] = 0;
    cout << "SQL error: " << state << " - " << code << " - " << buf << endl;
    exit(1);
}

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

// construct instance
OldOdbc::OldOdbc(const char *dsn, const char *un, const char *pw)
{
    int stat;
    stat = SQLAllocEnv(&env);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
      OtherExit("Error allocating environment");
    }
    stat = SQLAllocConnect(env, &con);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        EnvExit();
    }
    stat = SQLConnect(con, (SQLCHAR *)dsn, (SQLSMALLINT)strlen(dsn),
                           (SQLCHAR *)un, (SQLSMALLINT)strlen(un),
                           (SQLCHAR *)pw, (SQLSMALLINT)strlen(pw));
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        EnvExit();
    }
}

OldOdbc::OldOdbc(const char *constr)
{
    int stat;
    stat = SQLAllocEnv(&env);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
      OtherExit("Error allocating environment");
    }
    stat = SQLAllocConnect(env, &con);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        EnvExit();
    }
    char resconstr[1024];
    short int resconstrlen;
    stat = SQLDriverConnect(con, NULL, (SQLCHAR *)constr, (SQLSMALLINT)strlen(constr),
                                       (SQLCHAR *)resconstr, (SQLSMALLINT)sizeof(resconstr), (SQLSMALLINT *)&resconstrlen,
                            SQL_DRIVER_NOPROMPT);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        EnvExit();
    }
}

// destruct instance
OldOdbc::~OldOdbc()
{
    SQLDisconnect(con);
    SQLFreeConnect(con);
    SQLFreeEnv(env);
}

// get f1 given f2
int OldOdbc::T1GetOne(const char *f2)
{
    int stat;
    // get statement
    const char *sqlstr = "SELECT f1 FROM t1 WHERE f2 = ?";
    SQLHSTMT stmt;
    stat = SQLAllocStmt(con, &stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        ConExit();
    }
    // prepare
    stat = SQLPrepare(stmt, (SQLCHAR *)sqlstr, strlen(sqlstr));
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // bind parameters
    stat = SQLBindParam(stmt, 1, SQL_C_CHAR, SQL_VARCHAR, strlen(f2), 0, (SQLPOINTER)f2, NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // execute
    stat = SQLExecute(stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // bind results
    long int f1;
    stat = SQLBindCol(stmt, 1, SQL_C_LONG, &f1, 0, NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // process result
    stat = SQLFetch(stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        OtherExit("Row not found");
        return 0; // will never be reached
    }
    // close statement
    SQLCloseCursor(stmt);
    SQLFreeStmt(stmt, 0);
    return f1;
}

// get all records
int OldOdbc::T1GetAll(struct t1 *buf, int bufsiz)
{
    int stat;
    // get statement
    const char *sqlstr = "SELECT f1,f2 FROM t1";
    SQLHSTMT stmt;
    stat = SQLAllocStmt(con, &stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        ConExit();
    }
    // execute
    stat = SQLExecDirect(stmt, (SQLCHAR *)sqlstr, strlen(sqlstr));
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // bind results
    long int f1;
    stat = SQLBindCol(stmt, 1, SQL_C_LONG, &f1, 0, NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    char f2[F2_MAX_LEN+1];
    SQLLEN lenf2;
    stat = SQLBindCol(stmt, 2, SQL_C_CHAR, f2, sizeof(f2), &lenf2);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // process result
    int count = 0;
    for(;;)
    {
        if(count >= bufsiz) break;
        stat = SQLFetch(stmt);
        if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO)) break;
        f2[lenf2] = 0;
        buf[count].f1 = f1;
        strcpy(buf[count].f2, f2);
        count++;
    }
    // close statement
    SQLCloseCursor(stmt);
    SQLFreeStmt(stmt, 0);
    return count;
}

// add record
void OldOdbc::T1Put(int f1, const char *f2)
{
    int stat;
    // get statement
    const char *sqlstr = "INSERT INTO t1 VALUES(?, ?)";
    SQLHSTMT stmt;
    stat = SQLAllocStmt(con, &stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        ConExit();
    }
    // prepare
    stat = SQLPrepare(stmt, (SQLCHAR *)sqlstr, strlen(sqlstr));
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // bind parameters
    stat = SQLBindParam(stmt, 1, SQL_C_LONG, SQL_INTEGER, 0, 0, &f1, NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    stat = SQLBindParam(stmt, 2, SQL_C_CHAR, SQL_VARCHAR, strlen(f2), 0, (SQLPOINTER)f2, NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // execute
    stat = SQLExecute(stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // check if OK
    SQLLEN n;
    stat = SQLRowCount(stmt, &n);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    if(n != 1)
    {
        OtherExit("INSERT did not insert 1 row");
    }
    // close statement
    SQLFreeStmt(stmt, 0);
}

// delete record
void OldOdbc::T1Remove(int f1)
{
    int stat;
    // get statement
    const char *sqlstr = "DELETE FROM t1 WHERE f1 = ?";
    SQLHSTMT stmt;
    stat = SQLAllocStmt(con, &stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        ConExit();
    }
    // prepare
    stat = SQLPrepare(stmt, (SQLCHAR *)sqlstr, strlen(sqlstr));
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // bind parameters
    stat = SQLBindParam(stmt, 1, SQL_C_LONG, SQL_INTEGER, 0, 0, &f1, NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // execute
    stat = SQLExecute(stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    // check if OK
    SQLLEN n;
    stat = SQLRowCount(stmt, &n);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        StmtExit(stmt);
    }
    if(n != 1)
    {
        OtherExit("DELETE did not delete 1 row");
    }
    // close statement
    SQLFreeStmt(stmt, 0);
}

void test(DB *db)
{
    // 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();
}

void test_dsn(const char *dsn, const char *un, const char *pw)
{
    cout << "DSN=" << dsn << endl;;
    // get database connection
    DB *db = new OldOdbc(dsn, un, pw);
    // test
    test(db);
    // release database connection
    delete db;
}

void test_dsnless(const char *constr)
{
    cout << "Connection string=" << constr << endl;;
    // get database connection
    DB *db = new OldOdbc(constr);
    // test
    test(db);
    // release database connection
    delete db;
}

int main()
{
#ifdef SQLSRVODBC
    test_dsn("ARNEPC4_SQLSRV", "", "");
    test_dsnless("Driver={SQL Server Native Client 11.0};Server=localhost;Database=Test;Trusted_Connection=yes;");
#endif
#ifdef MYSQLODBC
    test_dsn("ARNEPC4_MYSQL", "root", "");
    test_dsnless("Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=Test;User=root;Password=;");
#endif
#ifdef DB2ODBC
    test_dsn("ARNEPC4_DB2", "", "");
    test_dsnless("Driver={IBM DB2 ODBC DRIVER};Hostname=localhost;Database=Test;Uid=arne;Pwd=xxxxxx;");
#endif
#ifdef ORACLEODBC
    test_dsn("ARNEPC4_ORACLE", "arne", "xxxxxx");
    test_dsnless("Driver={Oracle in instantclient_11_2};dbq=localhost/XE;Uid=arne;Pwd=xxxxxx;");
#endif
#ifdef PGSQLODBC
    test_dsn("ARNEPC4_PGSQL", "", "");
    test_dsnless("Driver={PostgreSQL ANSI(x64)};Server=localhost;Port=5432;Database=Test;Uid=postgres;Pwd=xxxxxx;");
#endif
#ifdef DB2CLI
    test_dsn("Test", "", "");
#endif
    return 0;
}
