/* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>

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

#define F2_MAX_LEN 50
#define MAX_REC 100

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

/* error handling functions */
void env_exit(SQLHENV env)
{
    unsigned char state[6], buf[200];
    long int code;
    short int buflen;
    SQLGetDiagRec(SQL_HANDLE_ENV, env, 1, state, &code, buf, sizeof(buf), &buflen);
    buf[buflen] = 0;
    printf("SQL error: %s - %ld - %s\n", state, code, buf);
    exit(1);
}

void con_exit(SQLHDBC con)
{
    unsigned char state[6], buf[200];
    long int code;
    short int buflen;
    SQLGetDiagRec(SQL_HANDLE_DBC, con, 1, state, &code, buf, sizeof(buf), &buflen);
    buf[buflen] = 0;
    printf("SQL error: %s - %ld - %s\n", state, code, buf);
    exit(1);
}

void stmt_exit(SQLHSTMT stmt)
{
    unsigned char state[6], buf[200];
    long int code;
    short int buflen;
    SQLGetDiagRec(SQL_HANDLE_STMT, stmt, 1, state, &code, buf, sizeof(buf), &buflen);
    buf[buflen] = 0;
    printf("SQL error: %s - %ld - %s\n", state, code, buf);
    exit(1);
}

void other_exit(char *msg)
{
    printf("%s\n", msg);
    exit(1);
}

/* get connection */
SQLHDBC get_connection_dsn(SQLHENV env, char *dsn, char *un, char *pw)
{
    SQLHDBC con;
    int stat;
    stat = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        env_exit(env);
    }
    stat = SQLAllocHandle(SQL_HANDLE_DBC, env, &con);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        env_exit(env);
    }
    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))
    {
        env_exit(env);
    }
    return con;
}

SQLHDBC get_connection_dsnless(SQLHENV env, char *constr)
{
    SQLHDBC con;
    char resconstr[1024];
    short int resconstrlen;
    int stat;
    stat = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        env_exit(env);
    }
    stat = SQLAllocHandle(SQL_HANDLE_DBC, env, &con);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        env_exit(env);
    }
    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))
    {
        env_exit(env);
    }
    return con;
}

/* get f1 given f2 */
int t1_get_one(SQLHDBC con, char *f2)
{
    SQLHSTMT stmt;
    char *sqlstr;
    long int f1;
    int stat;
    /* get statement */
    sqlstr = "SELECT f1 FROM t1 WHERE f2 = ?";
    stat = SQLAllocHandle(SQL_HANDLE_STMT, con, &stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        con_exit(con);
    }
    /* prepare */
    stat = SQLPrepare(stmt, (SQLCHAR *)sqlstr, strlen(sqlstr));
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* bind parameters */
    stat = SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, strlen(f2), 0, f2, strlen(f2), NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* execute */
    stat = SQLExecute(stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* bind results */
    stat = SQLBindCol(stmt, 1, SQL_C_LONG, &f1, 0, NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* process result */
    stat = SQLFetch(stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        other_exit("Row not found");
        return 0; /* will never be reached */
    }
    /* close statement */
    SQLCloseCursor(stmt);
    SQLFreeHandle(SQL_HANDLE_STMT, stmt);
    return f1;
}

/* get all records */
int t1_get_all(SQLHDBC con, struct t1 *buf, int bufsiz)
{
    SQLHSTMT stmt;
    char *sqlstr, f2[F2_MAX_LEN+1];
    SQLLEN lenf2;
    long int f1;
    int stat, count;
    /* get statement */
    sqlstr = "SELECT f1,f2 FROM t1";
    stat = SQLAllocHandle(SQL_HANDLE_STMT, con, &stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        con_exit(con);
    }
    /* execute */
    stat = SQLExecDirect(stmt, (SQLCHAR *)sqlstr, strlen(sqlstr));
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* bind results */
    stat = SQLBindCol(stmt, 1, SQL_C_LONG, &f1, 0, NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    stat = SQLBindCol(stmt, 2, SQL_C_CHAR, f2, sizeof(f2), &lenf2);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* process result */
    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);
    SQLFreeHandle(SQL_HANDLE_STMT, stmt);
    return count;
}

/* add record */
void t1_put(SQLHDBC con, int f1, char *f2)
{
    SQLHSTMT stmt;
    char *sqlstr;
    SQLLEN n;
    int stat;
    /* get statement */
    sqlstr = "INSERT INTO t1 VALUES(?, ?)";
    stat = SQLAllocHandle(SQL_HANDLE_STMT, con, &stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        con_exit(con);
    }
    /* prepare */
    stat = SQLPrepare(stmt, (SQLCHAR *)sqlstr, strlen(sqlstr));
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* bind parameters */
    stat = SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_LONG, SQL_INTEGER, 0, 0, &f1, 0, NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    stat = SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, strlen(f2), 0, f2, strlen(f2), NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* execute */
    stat = SQLExecute(stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* check if OK */
    stat = SQLRowCount(stmt, &n);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    if(n != 1)
    {
        other_exit("INSERT did not insert 1 row");
    }
    /* close statement */
    SQLFreeHandle(SQL_HANDLE_STMT, stmt);
}

/* delete record */
void t1_remove(SQLHDBC con, int f1)
{
    SQLHSTMT stmt;
    char *sqlstr;
    SQLLEN n;
    int stat;
    /* get statement */
    sqlstr = "DELETE FROM t1 WHERE f1 = ?";
    stat = SQLAllocHandle(SQL_HANDLE_STMT, con, &stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        con_exit(con);
    }
    /* prepare */
    stat = SQLPrepare(stmt, (SQLCHAR *)sqlstr, strlen(sqlstr));
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* bind parameters */
    stat = SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_LONG, SQL_INTEGER, 0, 0, &f1, 0, NULL);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* execute */
    stat = SQLExecute(stmt);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    /* check if OK */
    stat = SQLRowCount(stmt, &n);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
        stmt_exit(stmt);
    }
    if(n != 1)
    {
        other_exit("DELETE did not delete 1 row");
    }
    /* close statement */
    SQLFreeHandle(SQL_HANDLE_STMT, stmt);
}

/* print all records */
void t1_dump(SQLHDBC con)
{
    struct t1 buf[MAX_REC];
    int i, n;
    n = t1_get_all(con, buf, MAX_REC);
    for(i = 0; i < n; i++)
    {
        printf("%d \"%s\"\n", buf[i].f1, buf[i].f2);
    }
}

void test(SQLHDBC con)
{
    int f1;
    /* test t1_get_one */
    f1 = t1_get_one(con, "BB");
    printf("%d\n", f1);
    /* test t1_get_all */
    t1_dump(con);
    /* test t1_put */
    t1_put(con, 999, "XXX");
    t1_dump(con);
    /* test t1_remove */
    t1_remove(con, 999);
    t1_dump(con);
}

void test_dsn(char *dsn, char *un, char *pw)
{
    SQLHENV env;
    SQLHDBC con;
    int stat;
    printf("DSN=%s\n", dsn);
    /* get connection */
    stat = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
      other_exit("Error allocating environment");
    }
    con = get_connection_dsn(env, dsn, un, pw);
    /* test */
    test(con);
    /* close connection */
    SQLDisconnect(con);
    SQLFreeHandle(SQL_HANDLE_DBC, con);
    SQLFreeHandle(SQL_HANDLE_ENV, env);
}

void test_dsnless(char *constr)
{
    SQLHENV env;
    SQLHDBC con;
    int stat;
    printf("Connection string=%s\n", constr);
    /* get connection */
    stat = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
    if((stat != SQL_SUCCESS) && (stat != SQL_SUCCESS_WITH_INFO))
    {
      other_exit("Error allocating environment");
    }
    con = get_connection_dsnless(env, constr);
    /* test */
    test(con);
    /* close connection */
    SQLDisconnect(con);
    SQLFreeHandle(SQL_HANDLE_DBC, con);
    SQLFreeHandle(SQL_HANDLE_ENV, env);
}

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