/*
 * NAME
 *	pg_submit
 *
 * SYNOPSIS
 *	pg_submit [-d database] [-p pghost] [-g gdi_debug] [-t]
 *
 * COMPILATION
 *	UCB:     s5make pg_submit
 *	SAIC:    make pg_submit
 *
 * OPTIONS
 *	-d database	Name of the database. Overrides PGDATABASE env
 *			variable.
 *	-g gdi_debug	Optional debug level. If set to 1, the dbConn,
 *			dbObj, and dbColDef will be output.
 *			If set to 2, some libgdipg.a verbose messages will 
 *			be output.
 *	-t		Sets PQtrace.
 *
 * SAMPLE USAGE
 * 	Access database jta:     pg_submit -d jta
 * 	Turn on debug:           pg_submit -d jta -g 1
 * 	Turn on verbose debug:   pg_submit -d jta -g 2
 * 	Turn on PQtrace:         pg_submit -d jta -t
 *
 * DESCRIPTION
 * 	pg_submit prompts for queries, then outputs the dbObj along with
 * 	any attribute definitions and data.
 *  
 * AUTHOR
 *	J. T. Anderson	June 1993
 *
 *	Adapted from a combination of Mari Mortell's tst_submit.c and
 *	interact_submit.c GDI test programs.
 */
#ifndef lint
static char     SccsId[] = "@(#)pg_submit.c	16.3 8/7/93";
#endif

#include <stdio.h>
#include <string.h>
#include "libgendb.h"
#include "gdi_turbo.h"

#define USAGE "Usage: pg_submit [-d database] [-p pghost] [-g gdi_debug] [-t]"

/****************************************************************************/
/*  main                                                                    */
/****************************************************************************/
void
main(argc, argv)
int        argc;
char      **argv;
{
	char		database[GDI_DBNAME_SIZE +1];
	char		pghost[80];
	int		c, i;
	dbConstr	*constr;
	dbConn		*dbconn = NULL;	
	int		debug = 0, trace = 0;	/* GDI debug and trace */
	extern char     *optarg;
	extern	int	atoi(), optind, opterr;

	char	query[300];		/* gdi_submit(): database query  */
	char	maxrecs_str[24];	/* to read in as a string */
	int	maxrecs = -1;		/* gdi_submit(): max records to get */
	dbObj  *result_obj;		/* gdi_submit(): stores query results*/

	/*========================================*
	 *========= Get arguments ================*
	 *========================================*/

	bzero(database, sizeof(database));
	bzero(pghost, sizeof(pghost));

	while ((c = getopt(argc, argv, "d:g:p:t")) != EOF)
	{
		switch(c)
		{
		case 'd':
			(void)strncpy (database, optarg, GDI_DBNAME_SIZE);
			database[GDI_DBNAME_SIZE] = '\0';
			break;
		case 'g':
			debug = atoi (optarg);
			break;
		case 'p':
			(void)strncpy (pghost, optarg, sizeof(pghost) - 1);
			pghost[sizeof(pghost) - 1] = '\0';
			break;
		case 't':
			trace++;
			break;
		default:
			fprintf(stderr, "%s\n", USAGE);
			exit(1);
                }
	}

	/*===============
	 * Initialize GDI
	 *===============
	 */
	if (gdi_init(argv[0]) == GDI_FAILURE)
	{
		fprintf (stderr, "gdi_init failed: %s\n", 
				GDI_ERROR_MSG( (dbConn *)NULL) );
		exit (GDI_FAILURE);
	}

	constr = &GDI_TURBO;

	/* ====================
	 * Connect to Database
	 * ====================
	 */
	(void) gdi_error_init(NULL, debug, GDI_WARNING, 
		GDI_NOT_USED, GDI_NOT_USED);

	if ((dbconn = gdi_open("postgres", NULL,NULL, database, pghost,NULL))
		== (dbConn *)NULL )
	{
		fprintf (stderr, "gdi_open failed: %s\n", 
				GDI_ERROR_MSG( (dbConn *)NULL) );
		exit (GDI_FAILURE);
	}

	/* ====================
	 * Set Debug & Trace
	 * ====================
	 */
	(void) gdi_error_init(dbconn, (dbDebug) debug, GDI_WARNING, 
		GDI_NOT_USED, GDI_NOT_USED);

	if(trace)
		gdi_trace(dbconn, TRUE, "");

	if(GDI_ERROR_DEBUG(dbconn))
		gdi_print_conn(dbconn);

	/* ====================
	 * Submit Queries
	 * ====================
	 */
	for (;;)
	{
		fprintf(stdout,
			"\n\nenter a query ( do not terminate with '\\g' )\n");
		fprintf(stdout, "control D to quit\n> ");
		
		if ( fgets(query, sizeof(query), stdin) == NULL)
			break;

		/* strip new line */
		i = strlen(query);
		query[i-1] = '\0';

		if(strlen(query) == 0)
			continue;
		
		if (!strncmp(query, "dbconn", 6))
		{
			gdi_print_conn(dbconn);
			continue;
		}
		else if (!strncmp(query, "maxrec", 6))
		{
			fprintf(stdout, 
			"enter the max rows to return (-1 returns all).\n# ");

			if(fgets(maxrecs_str, sizeof(maxrecs_str), stdin)==NULL)
				break;

			/* strip new line */
			maxrecs_str[strlen(maxrecs_str)-1] = '\0';
			maxrecs = atoi(maxrecs_str);
			continue;
		}

		/*===========================================================*
		 *========= Submit the query ================================*
		 *===========================================================*/

		if ( gdi_submit(dbconn, query, maxrecs, constr, &result_obj))
		{
			fprintf (stderr, "gdi_submit failed: %s\n", 
				GDI_ERROR_MSG(dbconn));
		}
		else
		{
			if(GDI_ERROR_DEBUG(dbconn))
				gdi_print_dbobj ( result_obj);

			if(GDI_OBJ_NUM_TUPLES(result_obj) > 0 )
			{		 
				if(GDI_ERROR_DEBUG(dbconn))
					gdi_print_coldefs ( result_obj);
				gdi_print_tuples( result_obj, GDI_FIXED_SPACE,
					TRUE);
			}	 
		}

		result_obj = gdi_obj_destroy (result_obj);
	}
	
	/*==================================================================*
	 *================= Close database connection ======================*
	 *==================================================================*/

	(void) gdi_close(dbconn);
	exit(GDI_SUCCESS);
}
