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

/*----------------------------------------------------------------*/
/*  Classic example of transferring money from saving account to  */
/*  checking account employing a ROLLBACK if either update fails  */
/*  and a COMMIT of the transaction if both update succeed	  */
/*								  */
/*  Run ACCOUNT.SQL via MSQL to initialize tables and data	  */
/*								  */
/*----------------------------------------------------------------*/

int main( void ) {

SQLTCUR   cur;		/* SQLBASE cursor number  */
SQLTRCD   rcd;		/* return code		  */

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

  /*
  ** CONNECT TO THE DATABASE
  */
  if (rcd = sqlcnc(&cur, "SQLBASE", 0, NULL)) {
    printf("FAILURE ON CONNECT %d\n",rcd);
    exit(1);
  }
  else
    printf("Connection Established \n");

  /*
  ** COMPILE AND EXECUTE UPDATE OF SAVINGS ACCOUNT
  */
  if (rcd = sqlcex(cur, savupdt, 0))
  {
    printf("FAILED UPDATING SAVINGS, rcd = %d\n",rcd);
    sqldis(cur);
    exit(1);
  }
  else
    printf("ONE HUNDRED DOLLARS SUBTRACTED FROM SAVINGS \n");

  /*
    COMPILE AND EXECUTE UPDATE OF CHECKING ACCOUNT
  */

  if (rcd = sqlcex(cur, chkupdt, 0))
  {
    printf("FAILED UPDATING CHECKING (TRANSACTION ROLLBACK), rcd = %d\n",rcd);
    sqlrbk(cur);
    sqldis(cur);
    exit(1);
  }
  else
    printf("ONE HUNDRED DOLLARS ADDED TO CHECKING \n");

  /*
    COMMIT TRANSACTION
  */

  if (rcd = sqlcmt(cur))
    printf("FAILURE ON COMMIT, rcd = %d\n",rcd);
  else
    printf("TRANFER FROM SAVINGS TO CHECKING COMPLETED \n");

  /*
    DISCONNECT FROM THE DATABASE
  */

  if (rcd = sqldis(cur))
    printf("FAILURE ON DISCONNECT %d\n",rcd);
  else
    printf("Disconnect Performed \n");

  return( 0 );
}
