/* SEQUENCE */

#include "tdhkit.h"
#include "shsql.h"
#define CREATE 0
#define SELECT 1

int
SHSQL_sequence( dbc, sql, mode, rtnsql )
int dbc;
char *sql;
int mode;
char *rtnsql; /* used when mode=SELECT */
{
int i, ix, stat, nf, newval;
char tablename[MAXPATH];
char alias[50];
char buf[512];
char *fields[5];
FILE *fp;

ix = 0;

GL_getok( sql, &ix );
GL_getok( sql, &ix );

if( mode == CREATE ) {
	/* first, see if _sequences table exists; if not, create it.. */
	sprintf( buf, "%s/data/_sequences", SHSQL_projdir );
	fp = fopen( buf, "r" );
	if( fp == NULL ) {
		fp = fopen( buf, "w" );
		if( fp == NULL ) return( SHSQL_err( 222, "can't create _sequences file", buf ));
		fprintf( fp, "tablename%cvalue%c\n", SHSQL_delim, SHSQL_delim );
		fclose( fp );
		}
	else fclose( fp );
	
	/* now add a row for the requested sequence.. */
	strcpy( tablename, GL_getok( sql, &ix ) );
	if( stricmp( tablename, "on" )==0 ) strcpy( tablename, GL_getok( sql, &ix ) );
	sprintf( buf, "update _sequences orinsert set tablename = '%s', value = 0 where tablename = '%s'", tablename, tablename );
	return( SHSQL_sql( dbc, buf ) );
	}

else if( mode == SELECT ) {
	for( i = 0; sql[i] != '\0'; i++ ) if( GL_member( sql[i], " \t\n()" )) sql[i] = ' ';
	strcpy( alias, "" );
	strcpy( tablename, GL_getok( sql, &ix ) );
	if( stricmp( tablename, "as" )==0 ) {
		strcpy( alias, GL_getok( sql, &ix ) );
		strcpy( tablename, GL_getok( sql, &ix ) );
		}

	if( stricmp( tablename, "from" ) != 0 ) return( SHSQL_err( 221, "sql select _sequence: 'from' expected", "" ) );
	strcpy( tablename, GL_getok( sql, &ix ) );

	SHSQL_lock( "_sequences" ); /* lock the data file.. lock will be nested (ignored) when this same process
					  calles sqlupd().. lock released after retrieval of new serialnum in api() */

	sprintf( buf, "select value from _sequences where tablename = '%s'", tablename );
	stat = SHSQL_sql( dbc, buf );
	stat += SHSQL_getrow( dbc, fields, &nf );
	if( stat != 0 ) return( SHSQL_err( stat, "sql select _sequence: error on retrieval of existing sequence number", "" ) );

	newval = atoi( fields[0] ) + 1;

	sprintf( buf, "update _sequences set value = %d where tablename = '%s'", newval, tablename );
	stat = SHSQL_sql( dbc, buf );
	if( stat != 0 ) return( SHSQL_err( stat, "sql select _sequence: error on update of sequence number", "" ) );

	if( alias[0] != '\0' ) sprintf( rtnsql, "select value as %s from _sequences where tablename = '%s'", alias, tablename );
	else sprintf( rtnsql, "select value from _sequences where tablename = '%s'", tablename );

	return( 0 );
	}
return( 0 );
}
