/*
		This simple example list existing database on
		a mSQL database engine running on the local host.

		It uses mSQL++ (based on the mSQL.library).
		Please note that there is no Error handling done in
		the code.
		mSQL++ provides a powerfull internal exception 
		handling which is used instead.

		This code is based on the original demo code 
		included in the mSQL.library stuff.
*/

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

#include <libraries/msql++.h>

FILE* con = stdout;

void main(int argc, char** argv)
{
	try
	{
		mSQL msql;

		m_result *sql_Result;

		msql.Connect(); // default = "localhost"

		// ------------------------------------------------------------
		// from the original demo:

		// Gets current DB list
		m_result *mre = msql.ListDBs();
		if(mre)
		{
			fprintf(con,"Database(s) available:\n");
			// Now display DB list
			m_row	mro;
			while(mro = msql.FetchRow(mre))
			{
				fprintf(con,"  · %s (%d)\n", mro[0],msql.NumFields(mre));
			}
			msql.FreeResult(mre);
		}
		else
		{
			// This will hardly happen, due to the Exception handling ;)

			fprintf(con,"ListDBs failed\n");
			fprintf(con,"%s\n", msql.GetErrMsg()); // Display err message
		}

		// ------------------------------------------------------------

		msql.CreateDB("MyPrivateDB");
		msql.SelectDB("MyPrivateDB");

		char sql_Query[] = "CREATE TABLE People("\
											"ID int not null,"\
											"Firstname char(50),"\
											"Lastname char(50) not null,"\
										")";

		msql.Query(sql_Query);
		msql.Query("CREATE INDEX idx_People ON People(ID)");

		strcpy(sql_Query,"INSERT INTO tbl_Customers "        \
									"(ID,Firstname,Lastname) "\
									"VALUES (1,'Jürgen','Schober')");
		msql.Query(sql_Query);
      fprintf(con,"INSERT INTO returned : %s\n", msql.GetErrMsg());

		strcpy(sql_Query,"SELECT Firstname, Lastname FROM People ORDER BY Lastname DESC");
		msql.Query(sql_Query);

		sql_Result = msql.StoreResult();
		long rows = msql.NumRows(sql_Result);

		fprintf(con,"Rows: %d\n",rows);
		for (int r = 0; r < rows; r++)
		{
			msql.DataSeek(sql_Result,r);
			m_row row = msql.FetchRow(sql_Result);
			long fields = msql.NumFields(sql_Result);
			for (int f = 0; f < fields; f++)
			{
				fprintf(con,"%s ",row[f]);
			}
				fprintf(con," (%d) \n",fields);
		}

		msql.FreeResult(sql_Result);
	}
	catch (AdacException e)
	{
		// Dump an EasyRequest on Failure !
		int r = e.Warn("'Simple' -  mSQL++ Error","Break|Continue");

		// or just print it:
		e.Print();
	}
}

void wbmain(struct WBStartup *argmsg)
{
	// Enable WB Start here.

	con = fopen("con://640/200/mSQL++ output console/Wait/Close","w+");

	main(0,NULL);

	fclose(con);
}
