/*

 to compile:
 gcc -g -I/path/to/mysql/include mysql_stmt_reset_bug.c -L/path/to/mysql/libmysql/.libs \
 -lmysqlclient -lz -lm -lssl -lcrypto -lcrypt mysql_stmt_reset_bug

*/

#include <mysql.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define myerror(msg) print_error(msg)
#define mysterror(stmt, msg) print_st_error(stmt, msg)

MYSQL  mysql; 

static void print_error(const char *msg)
{
  if (&mysql && mysql_errno(&mysql))
  {
    if (&mysql.server_version)
      fprintf(stdout, "\n [MySQL-%s]", &mysql.server_version);
    else
      fprintf(stdout, "\n [MySQL]");
    fprintf(stdout, "[%d] %s\n", mysql_errno(&mysql), mysql_error(&mysql));
  }
  else if (msg) fprintf(stderr, " [MySQL] %s\n", msg);
}


static void print_st_error(MYSQL_STMT *stmt, const char *msg)
{
  if (stmt && mysql_stmt_errno(stmt))
  {
    if (stmt->mysql && stmt->mysql->server_version)
      fprintf(stdout, "\n ERROR: [MySQL-%s]", stmt->mysql->server_version);
    else
      fprintf(stdout, "\n [MySQL]");

    fprintf(stdout, "[%d] %s\n", mysql_stmt_errno(stmt),
            mysql_stmt_error(stmt));
  }
  else if (msg)
    fprintf(stderr, " [MySQL] %s\n", msg);
}

int main(int argc, char **argv)
{

  MYSQL_STMT    * stmt;
  MYSQL_RES     * result;
  char          * statement = "insert into t1 values (1)";
  
  mysql_init(&mysql);
  mysql_real_connect(&mysql,"localhost","root","","test",0,NULL, 0);

  mysql_query(&mysql, "drop table t1 if exists");
  mysql_query(&mysql, "create table t1(a int)");
  
  if (!(stmt = mysql_stmt_init(&mysql)))
  {
    myerror("Can't init stmt\n");
  }

  if (mysql_stmt_prepare(stmt, statement, strlen(statement)))
  {
    mysterror(stmt, "Can't prepare stmt\n");
  }

  mysql_query(&mysql, "drop table t1");

  fprintf(stderr, " Trying to execute statement that should fail on execute stage\n");
  if (mysql_stmt_execute(stmt))
  {
    mysterror(stmt, " Can't execute stmt\n");
    fprintf(stderr, "\n Error occurred during execute. Reset stmt\n\n");
    mysql_stmt_reset(stmt);
  }

  fprintf(stderr, " ** Stmt was reseted but error still exist\n");
  mysterror(stmt, "");

  mysql_query(&mysql, "create table t1(a int)");

  fprintf(stderr, "\n Trying to execute statement that should pass ok\n\n");
  if (mysql_stmt_execute(stmt))
  {
    mysterror(stmt, " Can't execute stmt\n");
    fprintf(stderr, "\n Error occurred during execute. Reset stmt\n\n");
    mysql_stmt_reset(stmt);
  }

  fprintf(stderr, " ** Stmt passed ok but error still exist\n");

  mysterror(stmt,"");

  mysql_stmt_close(stmt);
  mysql_close(&mysql);

  return 0;
}
