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



#define MAX_PATH 200

static int callback(void *p_data, int num_fields, char **p_fields, char **p_col_name)
{
     printf(" %s ", p_fields[0]);
     printf(" %s ", p_fields[1]);
     printf(" %s ", p_fields[2]);
     printf(" %s \n", p_fields[3]);
     return 1;
}



void
create_db_tables()
{
    char name[MAX_PATH +1];
    int ret, nrecs =0;
    char *errmsg =0;
    sqlite3 *db;
    char *statement =0;


    /* begin creating tables */
    snprintf(name, MAX_PATH +1, "/tmp/%s", "testdb");
    puts("\nCreating a database...");
    ret = sqlite3_open(name, &db);
    if(ret)
    {
       printf("ERROR: Can't create sqlite3 database.\n");
       exit(1);
    }
    
   puts("Creating a table..."); 
   ret = sqlite3_exec(db, 
		   "create table Categories(catId integer primary key, catName varchar(40), weight float, dropLowest integer)", 0, 0,0);
   if(ret)
   {
      sqlite3_close(db);
      printf("ERROR: Can't create table in sqlite3 database.\n");
      exit(1);
   }

    puts("Inserting some data...");
    statement = sqlite3_mprintf(  
      "insert into Categories values(%d, '%q', 1, %d)",
			       12345, "Hello world!", 0);
    if(statement)
    {
       ret = sqlite3_exec(db, statement, 0,0,0);
       if(ret)
       {
          sqlite3_free(statement);
          sqlite3_close(db);
          printf("ERROR: Can't insert data into table.\n");
          exit(1);
       }
       sqlite3_free(statement);
    }
    else
    {
          printf("ERROR: sqlite3_mprintf failed.\n");
          sqlite3_close(db);
          exit(1);
    }
    
    puts("Performing a query...");
    ret = sqlite3_exec(db, "select * from Categories", callback, &nrecs, &errmsg);
    if(errmsg)
    {
          printf("ERROR: Can't query db \n");
	  sqlite3_free(errmsg);
          sqlite3_close(db);
          exit(1);

    }    
    sqlite3_close(db);
    puts("sqlite3 tests passed!!\n");
    unlink(name);
}


int
main ()
{

  create_db_tables();
  return 0;			

}


