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

/* DBLIB headers */
#include <sybfront.h>
#include <sybdb.h>
#include <syberror.h>

#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 tds_exit(char *func)
{
    printf("TDS error in %s\n", func);
    exit(1);
}

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

static int err_handler(DBPROCESS *con, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr)
{
    if(severity > EXINFO)
    {
        printf("TDS DBLIB error: %s\n", dberrstr);
        if(oserr != DBNOERR)
        {
            printf("TDS OS error: %s\n", oserrstr);
        }
    }
    if((con == NULL) || DBDEAD(con)) return INT_EXIT;
    return INT_CANCEL;
}

static int msg_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvnam, char *proicnam, int line)
{
    if(severity > EXINFO)
    {
        printf("TDS Server error: %s\n", msgtext);
    }
    return 0;
}

/* poor mans escape */
static void escape(char *outbuf, int outbuflen, char *inbuf)
{
    int ix, i;
    ix = 0;
    for(i = 0; i <= strlen(inbuf); i++)
    {
        outbuf[ix] = inbuf[i];
        ix++;
        if(inbuf[i] == '\'')
        {
            outbuf[ix] = inbuf[i];
            ix++;
        }
    }
}

/* get connection */
DBPROCESS *get_connection(char *server, char *un, char *pw, char *db)
{
    DBPROCESS *con;
    LOGINREC *login;
    RETCODE stat;
    stat = dbinit();
    if(stat != SUCCEED) tds_exit("dbinit");
    dberrhandle(err_handler);
    dbmsghandle(msg_handler);
    login = dblogin();
    if(login == NULL) tds_exit("dblogin");
    stat = DBSETLUSER(login, un);
    if(stat != SUCCEED) tds_exit("DBSETLUSER");
    stat = DBSETLPWD(login, pw);
    if(stat != SUCCEED) tds_exit("DBSETLPWD");
    con = dbopen(login, server);
    if(con == NULL) tds_exit("dbopen");
    dbloginfree(login);
    stat = dbuse(con, db);
    if(stat != SUCCEED) tds_exit("dbuse");
    return con;
}

/* get f1 given f2 */
int t1_get_one(DBPROCESS *con, char *f2)
{
    // 
    RETCODE stat;
    char f2esc[2 * F2_MAX_LEN];
    /* build command */
    int f1;
    escape(f2esc, sizeof(f2esc), f2);
    stat = dbfcmd(con, "SELECT f1 FROM t1 WHERE f2 = '%s'", f2esc);
    if(stat != SUCCEED) tds_exit("dbcmd");
    /* execute */
    stat = dbsqlexec(con);
    if(stat != SUCCEED) tds_exit("dbsqlexec");
    /* bind results */
    stat = dbresults(con);
    if(stat != SUCCEED) tds_exit("dbresults");
    stat = dbbind(con, 1, INTBIND, 0, (BYTE *)&f1);
    if(stat != SUCCEED) tds_exit("dbbind");
    /* process results */
    if(dbnextrow(con) != NO_MORE_ROWS)
    {
          return f1;
    }
    else
    {
        other_exit("Row not found");
        return 0; /* will never be reached */
    }
}

/* get all records */
int t1_get_all(DBPROCESS *con, struct t1 *buf, int bufsiz)
{
    RETCODE stat;
    char f2[F2_MAX_LEN];
    int f1, count;
    /* build command */
    stat = dbcmd(con, "SELECT f1,f2 FROM t1");
    if(stat != SUCCEED) tds_exit("dbcmd");
    /* execute */
    stat = dbsqlexec(con);
    if(stat != SUCCEED) tds_exit("dbsqlexec");
    /* bind results */
    stat = dbresults(con);
    if(stat != SUCCEED) tds_exit("dbresults");
    stat = dbbind(con, 1, INTBIND, 0, (BYTE *)&f1);
    if(stat != SUCCEED) tds_exit("dbbind");
    stat = dbbind(con, 2, STRINGBIND, 0, (BYTE *)f2); /* using varlen=sizeof(f2) result in padding with spaces */
    if(stat != SUCCEED) tds_exit("dbbin");
    /* process results */
    count = 0;
    while((dbnextrow(con) != NO_MORE_ROWS)  && (count < bufsiz))
    {
        buf[count].f1 = f1;
        strcpy(buf[count].f2, f2);
        count++;
    }
    return count;
}

/* add record */
void t1_put(DBPROCESS *con, int f1, char *f2)
{
    RETCODE stat;
    char f2esc[2 * F2_MAX_LEN];
    int n;
    /* build command */
    escape(f2esc, sizeof(f2esc), f2);
    stat = dbfcmd(con, "INSERT INTO t1 VALUES(%d, '%s')", f1, f2esc);
    if(stat != SUCCEED) tds_exit("dbcmd");
    /* execute */
    stat = dbsqlexec(con);
    if(stat != SUCCEED) tds_exit("dbsqlexec");
    /* check if OK */
    n = DBCOUNT(con);
    if(n != 1)
    {
        other_exit("INSERT did not insert 1 row");
    }
}

/* delete record */
void t1_remove(DBPROCESS *con, int f1)
{
    RETCODE stat;
    int n;
    /* build command */
    stat = dbfcmd(con, "DELETE FROM t1 WHERE f1 = %d", f1);
    if(stat != SUCCEED) tds_exit("dbcmd");
    /* execute */
    stat = dbsqlexec(con);
    if(stat != SUCCEED) tds_exit("dbsqlexec");
    /* check if OK */
    n = DBCOUNT(con);
    if(n != 1)
    {
        other_exit("DELETE did not delete 1 row");
    }
}

/* print all records */
void t1_dump(DBPROCESS *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);
    }
}

int main()
{
    DBPROCESS *con;
    int f1;
    /* get connection */
#ifdef FREETDS
    con = get_connection("ARNEPC4\\SQLEXPRESS", "", "", "Test");
#endif
#ifdef SYBASE
    con = get_connection("ARNEPC4", "sa", "xxxxxx", "Test");
#endif
    /* 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);
    /* close connection */
    dbclose(con);
    dbexit();
    return 0;
}
