/*
 * KEY.C
 * WADE 6/1/89, Modified by SMF 7/13/89
 **
 * This program searches an Ingres database to perform a retrieve on a
 * "keyword" string in the "keyword" data file.  GDB is used to perform the
 * query over the network.  A list of id's is returned if the search was
 * successfull.  Return # of ID's found or a negative error code.
 */

#include <stdio.h>
#include <gdb.h>

char		*fld_names[] = {"id"};
FIELD_TYPE	fld_types[] = {STRING_T};
DATABASE	wadetest;			/* INGRES dbid location */

#define ID		0		/* first field in the tuple         */
#define QUERYSIZE	130		/* max QUEL statement to ingres     */

/*
 * <dbid@host-node:service-id>
 */
#define SERVICE_NAME	"wadetest@elsa.mit.edu:gdb3"

/*
 * QUEL retrieve command
 */
#define QUERY	"(>*id*<=keyword.id) where keyword.phrase = \""


int
key_search(key_word, key_func)
char   key_word[];		/* phrase for QUEL retrieve command */
void	(*key_func)();
{
	TUPLE_DESCRIPTOR	desc;
	STRING			*id;
	RELATION		result;
	TUPLE			t;

	int	hits, rc;
	int     keyword_size;
	char	query[QUERYSIZE];

	/*
	 * do not place characters past the storage allocated by var query
	 * length(QUERY) + length(key_word) + * + " + \0 <= QUERYSIZE
	 */
	keyword_size = strlen(key_word);
	if (strlen(QUERY) + keyword_size + 3 > QUERYSIZE) {
		/*
		 * printf("*** %s exceeds %d characters
		 * ***\n",word,QUERYSIZE);  
		 */
/*		disp_setmsg("Keyword exceeds maximum limit.");  */
		return -10;
	} else 
		sprintf(query, "%s%s*\"", QUERY, key_word);

	/*
	 * initialize data structures used by GDB
	 */
	gdb_init();
	desc = create_tuple_descriptor(1, fld_names, fld_types);
	result = create_relation(desc);

	/* printf("Attempting to connect to database\n"); */
	access_db(SERVICE_NAME, &wadetest);

	/*
	 * test result of dbserv attempting to locate database
	 */
	switch (DB_STATUS(wadetest)) {
	case DB_OPEN:
		/* printf("Searching for: %s\n", word); */
		break;
	case DB_CLOSED:
		/*
		 * printf("*** Could not connect to database wadetest
		 * ***\n"); 
		 */
/*		disp_errmsg("Keyword database server is not available (no lockmgr).");  */
		return -11;
	}

	rc = db_query(wadetest, result, query);
	if (rc != OP_SUCCESS) {
		/* printf("*** GDB return code: %d ***\n",rc); */
/*		disp_errmsg("Keyword database server is unavailable.");  */
		return -rc;
	}
	hits = tuples_in_relation(result);

	for (t = FIRST_TUPLE_IN_RELATION(result); t;
	     t = NEXT_TUPLE_IN_RELATION(result, t)) {

		id = (STRING *) FIELD_FROM_TUPLE(t, ID);
		
		(*key_func)(atol(STRING_DATA(*id)), 0);
		
		delete_tuple(t);
	}

	terminate_db(&wadetest);

	return hits;
}
