#include <stdio.h>
#include "sql.h"

/*----------------------------------------------------------------*/
/*								  */
/*  Example employing common error routine			  */
/*								  */
/*  Run ACCOUNT.SQL via MSQL to establish tables and amounts.     */
/*								  */
/*----------------------------------------------------------------*/

	  SQLTCUR   cur;		/* SQLBASE cursor number  */
	  SQLTRCD   rcd;		/* error number 	  */
	  SQLTRBF   rbf;		/* rollback flag	  */
	  char	    errmsg[SQLMERR];	/* error msg text buffer  */

	  main()
{

static	  char	    savupdt [] =	/* UPDATE savings command */
"UPDATE SAVINGS SET SAV_DOLLARS = SAV_DOLLARS - 100 WHERE SAV_ACC_NO = 951";

static	  char	    chkupdt [] =	/* UPDATE checking command*/
"UPDATE CHECKING SET CHK_DOLLARS = CHK_DOLLARS + 100 WHERE CHK_ACC_NO = 1495";

  rbf = 0;				/* initialize rollback	  */

  /*
    CONNECT TO THE DATABASE
  */

  if (rcd = sqlcnc(&cur, "SQLBASE", 0, NULL))
  {
    sqlerr(rcd, errmsg);		/* get error message text */
    printf("%s \n",errmsg);
    exit(1);
  }
  else
    printf("Connection Established \n");

  /*
    COMPILE AND EXECUTE UPDATE OF SAVINGS ACCOUNT
  */

  if (sqlcex(cur, savupdt, 0))
    failure("UPDATE OF SAVINGS");
  else
    printf("ONE HUNDRED DOLLARS SUBTRACTED FROM SAVINGS \n");

  /*
    COMPILE AND EXECUTE UPDATE OF CHECKING ACCOUNT
  */

  if (sqlcex(cur, chkupdt, 0))
  {
    rbf = 1;
    failure("UPDATE OF CHECKING");
  }
  else
    printf("ONE HUNDRED DOLLARS ADDED TO CHECKING \n");

  /*
    COMMIT TRANSACTION
  */

  if (rcd = sqlcmt(cur))
    failure("COMMIT");
  else
    printf("TRANFER FROM SAVINGS TO CHECKING COMPLETED \n");

  /*
    DISCONNECT FROM THE DATABASE
  */

  if (rcd = sqldis(cur))
    failure("DISCONNECT");
  else
    printf("Disconnect Performed \n");
}

	  failure(ep)

	  char*     ep; 		/* -> failure msg string  */
{
	  SQLTEPO   epo;		/* error position	  */

  printf("Failure on %s \n", ep);

  sqlrcd(cur, &rcd);			/* get the error	  */
  sqlepo(cur, &epo);			/* get error position	  */

  if (rbf)				/* need a rollback?	  */
    sqlrbk(cur);
  else
    sqlrbf(cur, &rbf);			/* get rollback flag	  */

  if (rbf)
    printf("TRANSACTION ROLLBACK \n");

  sqlerr(rcd, errmsg);			/* get error message text */
  sqldis(cur);
  printf("%s (error: %u, position: %u) \n",errmsg,rcd,epo);

  exit(1);
}
