/* test program for CSC issue #34651
   compile with:
     gcc -o test1 -DRECONNECT=0 `mysql_config --cflags --libs` 34651.c
     gcc -o test2 -DRECONNECT=1 `mysql_config --cflags --libs` 34651.c
   then run as: ./test and restart MySQL server when asked
 */

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

#define ZERO(F) \
if (F) {\
    printf("Error: 0 != %s\n", #F);\
    printf("MySQL error: %d - %s\n", mysql_errno(mysql), mysql_error(mysql));\
    exit(1);\
} else\
    printf("OK: %s\n", #F);

#define SZERO(F) \
if (F) {\
    printf("Error: 0 != %s\n", #F);\
    printf("MySQL error: %d - %s\n", mysql_stmt_errno(stmt), mysql_stmt_error(stmt));\
} else\
    printf("OK: %s\n", #F);

#define NONZERO(F) \
if (!(F)) {\
    printf("Error: 0 == %s\n", #F);\
    exit(1);\
} else\
    printf("OK: %s\n", #F);


#define BUFSIZE 20
char *values[] = {"eins", "zwei", "drei", "viele", NULL};

#define DROP   "DROP TABLE IF EXISTS t1"
#define CREATE "CREATE TABLE t1 (c1 INT PRIMARY KEY AUTO_INCREMENT, c2 CHAR(10))"
#define INSERT "INSERT INTO t1 (c2) VALUES (?)"


int main (void)
{
    MYSQL *mysql;
    MYSQL_RES  *res;
    my_bool reconnect= RECONNECT;

    unsigned int i;

    //connect to MySQL
    NONZERO(mysql= mysql_init(NULL));
    ZERO(mysql_options(mysql, MYSQL_OPT_RECONNECT, &reconnect));
    NONZERO(mysql_real_connect(mysql, "127.0.0.1", NULL, NULL, "test", 0, NULL, 0));

   //create a table
    ZERO(mysql_query(mysql, DROP));
    ZERO(mysql_query(mysql, CREATE));

    //insert some rows
    {
        MYSQL_STMT *stmt;
        MYSQL_BIND bind;
        char buffer[BUFSIZE];
        my_bool is_null= 0;
        unsigned long length;

        //create statement handle
        NONZERO(stmt= mysql_stmt_init(mysql));
        ZERO(mysql_stmt_prepare(stmt, INSERT, strlen(INSERT)));

        //prepare parameter bind
        bind.buffer_type= MYSQL_TYPE_STRING;
        bind.buffer_length= BUFSIZE;
        bind.buffer= buffer;
        bind.is_null= &is_null;
        bind.length= &length;

        //bind params to statement
        ZERO(mysql_stmt_bind_param(stmt, &bind));

        //insert 4 rows
        for (i= 0; values[i]; i++) {
            if (i == 2) {
                printf("please restart MySQL server and press <return>\n");
                getc(stdin);
            }
            strncpy(buffer, values[i], BUFSIZE);
            length= strlen(buffer);

            //execute statement
            SZERO(mysql_stmt_execute(stmt));
        }

        //close statement
        ZERO(mysql_stmt_close(stmt));
    }

    //cleanup
    ZERO(mysql_query(mysql, DROP));

    //close connection
    mysql_close(mysql);

    printf("complete\n");
}

