// 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>
using namespace std;

// ADO headers
#include <windows.h>
#import "msado15.dll" rename("EOF", "EndOfFile")
using namespace ADODB;

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

// utility function
static void bstr2char(char *out, BSTR in)
{
    int len = SysStringLen(in);
    for(int i = 0; i < len; i++)
    {
        out[i] = (char)in[i];
    }
    out[len] = 0;
}

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 ADO : public DB
{
private:
    _ConnectionPtr con;
    void ExceptionExit(_com_error ex);
    void OtherExit(const char *msg);
public:
    // construct instance
    ADO(const char *constr, const char *un, const char *pw);
    // destruct instance
    virtual ~ADO();
    // 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 ADO::ExceptionExit(_com_error ex)
{
    cout << "COM error: " << ex.ErrorMessage() << ", ADO error: " << ex.Description()  << endl;
    exit(1);
}

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

// construct instance
ADO::ADO(const char *constr, const char *un, const char *pw)
{
    try
    {
        con.CreateInstance(__uuidof(Connection));
        con->Open(constr, un, pw, adConnectUnspecified);
    }
    catch(_com_error &ex)
    {
        ExceptionExit(ex);
    }
}

// destruct instance
ADO::~ADO()
{
    con->Close();
    con = NULL;
}

// get f1 given f2
int ADO::T1GetOne(const char *f2)
{
    try
    {
        // create command
        _CommandPtr cmd;
        cmd.CreateInstance(__uuidof(Command));
        cmd->ActiveConnection = con;
        cmd->CommandText = "SELECT f1 FROM t1 WHERE f2 = ?";
        cmd->NamedParameters = false;
        // add parameter
        _ParameterPtr p = cmd->CreateParameter("", adVarChar, adParamInput, -1);
        p->Value = f2;
        cmd->Parameters->Append(p);
        // open record set
        _RecordsetPtr rs = cmd->Execute(NULL, NULL, adCmdText);
        // process result
        int f1;
        if(!rs->EndOfFile)
        {
            f1 = rs->GetCollect("f1").intVal;
        }
        else
        {
            OtherExit("Row not found");
            return 0; // will never be reached
        }
        // close record set
        rs->Close();
        rs = NULL;
        cmd = NULL;
        return f1;
    }
    catch(_com_error &ex)
    {
        ExceptionExit(ex);
        return 0; // will never be reached
    }
}

// get all records
int ADO::T1GetAll(struct t1 *buf, int bufsiz)
{
    try
    {
        // create command
        _CommandPtr cmd;
        cmd.CreateInstance(__uuidof(Command));
        cmd->ActiveConnection = con;
        cmd->CommandText = "SELECT * FROM t1";
        // open record set
        _RecordsetPtr rs = cmd->Execute(NULL, NULL, adCmdText);
        // process result
        int count = 0;
        while(!rs->EndOfFile && (count < bufsiz))
        {
            buf[count].f1 = rs->GetCollect("f1").intVal;
            bstr2char(buf[count].f2, rs->GetCollect("f2").bstrVal);
            count++;
            rs->MoveNext();
        }
        // close record set
        rs->Close();
        rs = NULL;
        cmd = NULL;
        return count;
    }
    catch(_com_error &ex)
    {
        ExceptionExit(ex);
        return 0; // will never be reached
    }
}

// add record
void ADO::T1Put(int f1, const char *f2)
{
    try
    {
        // create command
        _CommandPtr cmd;
        cmd.CreateInstance(__uuidof(Command));
        cmd->ActiveConnection = con;
        cmd->CommandText = "INSERT INTO t1 VALUES(?, ?)";
        cmd->NamedParameters = false;
        // add parameters
        _ParameterPtr p1 = cmd->CreateParameter("", adInteger, adParamInput, -1);
        p1->Value = f1;
        cmd->Parameters->Append(p1);
        _ParameterPtr p2 = cmd->CreateParameter("", adVarChar, adParamInput, -1);
        p2->Value = f2;
        cmd->Parameters->Append(p2);
        // execute
        _variant_t n;
        cmd->Execute(&n, NULL, adCmdText);
        // check if OK
        if(n.intVal != 1)
        {
            OtherExit("INSERT did not insert 1 row");
        }
    }
    catch(_com_error &ex)
    {
        ExceptionExit(ex);
    }
}

// delete record
void ADO::T1Remove(int f1)
{
    try
    {
        // create command
        _CommandPtr cmd;
        cmd.CreateInstance(__uuidof(Command));
        cmd->ActiveConnection = con;
        cmd->CommandText = "DELETE FROM t1 WHERE f1 = ?";
        cmd->NamedParameters = false;
        // add parameters
        _ParameterPtr p = cmd->CreateParameter("", adInteger, adParamInput, -1);
        p->Value = f1;
        cmd->Parameters->Append(p);
        // execute
        _variant_t n;
        cmd->Execute(&n, NULL, adCmdText);
        // check if OK
        if(n.intVal != 1)
        {
            OtherExit("DELETE did not delete 1 row");
        }
    }
    catch(_com_error &ex)
    {
        ExceptionExit(ex);
    }
}

void test(const char *constr, const char *un, const char *pw)
{
    cout << "Connection string=" << constr << endl;
    // get database connection
    DB *db = new ADO(constr, un, pw);
    // 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;
}


int main()
{
    CoInitialize(NULL);
#ifdef SQLSRV
    test("Provider=SQLNCLI11;Server=localhost;Database=Test;Trusted_Connection=yes;", "", "");
    test("Driver={SQL Server Native Client 11.0};Server=localhost;Database=Test;Trusted_Connection=yes;", "", "");
#endif
#ifdef DB2
    test("Provider=IBMDADB2;Protocol=TCPIP;Hostname=localhost;Database=Test;Port=50000;Uid=arne;Pwd=xxxxxx;", "", "");
    test("Driver={IBM DB2 ODBC DRIVER};Hostname=localhost;Database=Test;Uid=arne;Pwd=xxxxxx;", "", "");
#endif
#ifdef ORACLE
    test("Provider=OraOLEDB.Oracle;Data Source=localhost:1521/XE;", "arne", "xxxxxx");
    test("Driver={Oracle in instantclient_11_2};Dbq=localhost/XE;;Uid=arne;Pwd=xxxxxx;", "", "");
#endif
    CoUninitialize();
    return 0;
}
