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

#include "common.h"

#define ARRAY_SIZE 100

int main(int argc, char **argv)
{
	SQLRETURN rc;
	HSTMT hstmt = SQL_NULL_HSTMT;
	char *sql;

	SQLINTEGER int_array[ARRAY_SIZE];
	SQLLEN ind_array[ARRAY_SIZE];
	SQLULEN rowsFetched[ARRAY_SIZE];
	SQLUSMALLINT rowStatus[ARRAY_SIZE];

	int i;

	test_connect();

	rc = SQLAllocStmt(conn, &hstmt);
	if (!SQL_SUCCEEDED(rc))
	{
		print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
		exit(1);
	}

	/* Prepare + Execute */
	sql = "SELECT generate_series(1,20)";
	rc = SQLPrepare(hstmt, (SQLCHAR *) sql, SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);

	rc = SQLExecute(hstmt);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);

	/* Set attributes */
	rc = SQLSetStmtAttr(hstmt, SQL_ATTR_ROWS_FETCHED_PTR, &rowsFetched, 0);
	CHECK_STMT_RESULT(rc, "SQLSetStmtAttr(SQL_ATTR_ROWS_FETCHED_PTR) failed", hstmt);
	rc = SQLSetStmtAttr(hstmt, SQL_ATTR_ROW_ARRAY_SIZE, (SQLPOINTER) 1, 0);
	CHECK_STMT_RESULT(rc, "SQLSetStmtAttr(SQL_ATTR_ROW_ARRAY_SIZE) failed", hstmt);
	rc = SQLSetStmtAttr(hstmt, SQL_ATTR_ROW_STATUS_PTR, &rowStatus, 0);
	CHECK_STMT_RESULT(rc, "SQLSetStmtAttr(SQL_ATTR_ROW_STATUS_PTR) failed", hstmt);

	/* Bind */
	rc = SQLBindCol(hstmt, 1, SQL_INTEGER, int_array, sizeof(SQLLEN), ind_array);
	CHECK_STMT_RESULT(rc, "SQLBindCol failed", hstmt);

	/* Fetch results with SQLFetchScroll */
	i = 0;
	while ((rc = SQLFetchScroll(hstmt, SQL_FETCH_NEXT, 0)) != SQL_NO_DATA)
	{
		i++;
		CHECK_STMT_RESULT(rc, "SQLFetchScroll failed", hstmt);
		printf("row %d: %d\n", i, int_array[0]);
	}

	/* Clean up */
	test_disconnect();

	return 0;
}
