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

// LIBOCI headers
#define OCI_API __stdcall
#include <ocilib.hpp>
using namespace ocilib;

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 LibOci : public DB
{
private:
    Connection con;
    void ExceptionExit(Exception ex);
    void OtherExit(const char *msg);
public:
    // construct instance
    LibOci(const char *db, const char *usr, const char *pw);
    // destruct instance
    virtual ~LibOci();
    // 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 LibOci::ExceptionExit(Exception ex)
{
    cout << "SQL error: " <<  ex.what() << endl;
    exit(1);
}

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

// construct instance
LibOci::LibOci(const char *db, const char *usr, const char *pw)

{
    con.Open(db, usr, pw, Environment::SessionDefault);
}

// destruct instance
LibOci::~LibOci()
{
}

// get f1 given f2
int LibOci::T1GetOne(const char *f2)
{
    try
    {
        // get statement
        const char *sqlstr = "SELECT f1,f2 FROM t1 WHERE f2 = :f2";
        Statement stmt(con);
        // prepare
        stmt.Prepare(sqlstr);
        // bind parameters
        ostring xf2(f2);
        stmt.Bind(":f2", xf2, xf2.length(), BindInfo::In);
        // execute
        stmt.ExecutePrepared();
        // process result
        int f1;
        Resultset rs = stmt.GetResultset();
        if (rs++) 
        {
            f1 = rs.Get<int>(1);
        }
        else
        {
            OtherExit("Row not found");
            return 0; // will never be reached
        }
        return f1;
    }
    catch (Exception &ex)
    {
        ExceptionExit(ex);
        return 0; // will never be reached
    }
}

// get all records
int LibOci::T1GetAll(struct t1 *buf, int bufsiz)
{
    try
    {
        // get statement
        const char *sqlstr = "SELECT f1,f2 FROM t1";
        Statement stmt(con);
        // execute
        stmt.Execute(sqlstr);
        // process result
        Resultset rs = stmt.GetResultset();
        int count = 0;
        while (rs++ && count < bufsiz)
        {
            buf[count].f1 = rs.Get<int>(1);
            strcpy(buf[count].f2, rs.Get<ostring>(2).c_str());
            count++;
        }
        return count;
    }
    catch (Exception &ex)
    {
        ExceptionExit(ex);
        return 0; // will never be reached
    }
}

// add record
void LibOci::T1Put(int f1, const char *f2)
{
    try
    {
        // get statement
        const char *sqlstr = "INSERT INTO t1 VALUES(:f1, :f2)";
        Statement stmt(con);
        // prepare
        stmt.Prepare(sqlstr);
        // bind parameters
        stmt.Bind(":f1", f1, BindInfo::In);
        ostring xf2(f2);
        stmt.Bind(":f2", xf2, xf2.length(), BindInfo::In);
        // execute
        stmt.ExecutePrepared();
        // check if OK
        if(stmt.GetAffectedRows() != 1)
        {
            OtherExit("INSERT did not insert 1 row");
        }
    }
    catch (Exception &ex)
    {
        ExceptionExit(ex);
    }
}

// delete record
void LibOci::T1Remove(int f1)
{
    try
    {
        // get statement
        const char *sqlstr = "DELETE FROM t1 WHERE f1 = :f1";
        Statement stmt(con);
        // prepare
        stmt.Prepare(sqlstr);
        // bind parameters
        stmt.Bind(":f1", f1, BindInfo::In);
        // execute
        stmt.ExecutePrepared();
        // check if OK
        if(stmt.GetAffectedRows() != 1)
        {
            OtherExit("DELETE did not delete 1 row");
        }
    }
    catch (Exception &ex)
    {
        ExceptionExit(ex);
    }
}

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_dsnless(const char *constr)
{
    cout << "Connection string=" << constr << endl;;
}

void test_oci(const char *dbnam, const char *usr, const char *pw)
{
    // get database connection
    DB *db = new LibOci(dbnam, usr, pw);
    // test
    test(db);
    // release database connection
    delete db;
}

int main()
{
    Environment::Initialize(Environment::Default | Environment::Threaded);
    test_oci("XE", "arne", "xxxxxx");
    Environment::Cleanup();
    return 0;
}
