#include <my_global.h>
#include <mysql.h>

#define SELECT123 "SELECT * FROM high_view"
#define SELECT234 "SELECT * FROM high_view where b = 1"

int main(int argc, char **argv)
{
	MYSQL *conn;
	MYSQL_STMT *prep_stmt = NULL;
	int res;
        int i, expect;

	const ulong type= (ulong)CURSOR_TYPE_READ_ONLY;
	
	mysql_library_init(argc, argv, NULL);

	if (!(conn = mysql_real_connect(mysql_init(NULL), "127.1.0.0", "jan", "jan", "test", 0, NULL, 0))) {
	        fprintf(stderr, "Could not connect\n");
		exit(1);
        }

	mysql_query(conn, "create table high_view(a int not null, b int, primary key(a)) engine = innodb");
	mysql_query(conn, "insert into high_view values(1, 1)");
        mysql_query(conn, "commit");

	mysql_query(conn, "set autocommit=0");
        
	
	prep_stmt= mysql_stmt_init(conn);

	mysql_stmt_attr_set(prep_stmt, STMT_ATTR_CURSOR_TYPE, (const void *)&type);
        mysql_query(conn, "insert into high_view values(2, 2)");
	res= mysql_stmt_prepare(prep_stmt, SELECT123 , strlen(SELECT123));
        mysql_query(conn, "insert into high_view values(3, 1)");
	res= mysql_stmt_execute(prep_stmt);
        mysql_query(conn, "insert into high_view values(4, 2)");

	i=0;
	printf("reading cursor 1\n");
	do {
		res = mysql_stmt_fetch(prep_stmt);
		if (res) break;
		printf("\trow has been read\n");
		i++;
	} while(1);

	expect = 3;
	printf("read %d expected %d %s\n", i, expect, i!=expect? "PROBLEM":"");

	res= mysql_stmt_close(prep_stmt);	
	res= mysql_query(conn, "commit");

	prep_stmt= mysql_stmt_init(conn);

	mysql_stmt_attr_set(prep_stmt, STMT_ATTR_CURSOR_TYPE, (const void *)&type);
        mysql_query(conn, "insert into high_view values(5, 1)");
	res= mysql_stmt_prepare(prep_stmt, SELECT234 , strlen(SELECT234));
        mysql_query(conn, "insert into high_view values(6, 1)");
	res= mysql_stmt_execute(prep_stmt);
        mysql_query(conn, "insert into high_view values(7, 1)");

	i=0;
	printf("reading cursor 2\n");
	do {
		res = mysql_stmt_fetch(prep_stmt);
		if (res) break;
		printf("\trow has been read\n");
		i++;
	} while(1);

	expect = 4;
	printf("read %d expected %d %s\n", i, expect, i!=expect? "PROBLEM":"");

	res= mysql_stmt_close(prep_stmt);	
	res= mysql_query(conn, "commit");

	mysql_query(conn, "drop table high_view;");
}
