/*
		msql.library TCP/IP stack vs mUSD speed test
		©1998 Christophe Sollet (cfc@iname.com)

*/

#include <exec/types.h>
#include <proto/exec.h>
#include <proto/msql.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

struct Library *MsqlBase;

void Test(struct MsqlConnection *);

main()
{
	struct MsqlConnection *co;

	if(MsqlBase = OpenLibrary("msql.library", 3))   /* Open the library */
	{
        /* Before doing any msql operation, we need a valid MsqlConnection structure */
		if(co = MsqlAllocConnection())
		{
            /* Now we'll attempt a connection on a local mSQL database engine */
			/* Using "localhost", we're connecting by the TCP/IP stack */
			if(MsqlConnect(co, "localhost"))
			{
				time_t stime = time(NULL), etime;
				double diff;
				Test(co);
				MsqlClose(co);
				etime = time(NULL);
				diff = difftime(etime, stime);
				printf("The test using TCP/IP stack took %.0f seconds\n", diff);
				
			} else
            {
                printf("Connection failed\n");
                printf("%s\n", MsqlGetErrMsg(co));
            }

            /* Now we'll attempt a connection on a local mSQL database engine */
			/* Using NULL, we're connecting by the mUSD */
			if(MsqlConnect(co, NULL))
			{
				time_t stime = time(NULL), etime;
				double diff;
				Test(co);
				MsqlClose(co);
				etime = time(NULL);
				diff = difftime(etime, stime);
				printf("The test using mUSD took %.0f seconds\n", diff);
			} else
            {
                printf("Connection failed\n");
                printf("%s\n", MsqlGetErrMsg(co));
            }


			MsqlFreeConnection(co);
		} else printf("Alloc failed\n");
		CloseLibrary(MsqlBase);
	} else printf("Open Libs failed\n");
}

void Test(struct MsqlConnection *co)
{
	m_result *mre, *mre2;
	m_row	dbname, tablename;

    /* Gets current DB list */
	mre = MsqlListDBs(co);
	if(mre)
	{
	    /* Get the name of the first db */
		if(dbname = MsqlFetchRow(mre))
		{
			printf("%s", *dbname);

			/* Select this db */
			if(MsqlSelectDB(co, *dbname) != -1)
			{
				printf(" selected\n");
				if(mre2 = MsqlListTables(co))
				{
           	        /* Get the name of the first table */
					if(tablename = MsqlFetchRow(mre2))
					{
						int i;
						char *query;
						if(query = calloc(strlen(*tablename)+16, sizeof(char)))
						{
							sprintf(query, "SELECT * FROM %s", *tablename);
							printf("\t'%s' 100 times\n", query);
							for(i=0; i<100; i++)
							{
								MsqlQuery(co, query);
								printf(".");
								fflush(stdout);
							}
							printf("\n");
							free(query);
						}
					}
				}
				MsqlFreeResult(mre2);
			}
			else
			{
				printf("\nSelectDB failed\n");
				printf("%s\n", MsqlGetErrMsg(co)); // Display err message
			}
		}
		MsqlFreeResult(mre);
	} else
	{
		printf("ListDBs failed\n");
		printf("%s\n", MsqlGetErrMsg(co)); // Display err message
	}
}
