/*

	My custom type to test PostgreSQL ANALYZE patch

*/


#include "postgres.h"
#include "fmgr.h"
#include "access/heapam.h"
#include "commands/vacuum.h"



static void compute_test_stats(VacAttrStats *stats,
					 TupleDesc tupDesc, double totalrows,
					 HeapTuple *rows, int numrows)
{

	/* Probably the most uninspired stats function of all time -
	place the number 999.999 in the array */
	MemoryContext old_context;
	float4 *value;
	int i;

	old_context = MemoryContextSwitchTo(stats->anl_context);
	value = (float4 *) palloc(sizeof(float4));
	*value = 999.999;
	MemoryContextSwitchTo(old_context);

	for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
	{
		stats->stakind[i] = STATISTIC_KIND_CUSTOM;
		stats->staop[i] = InvalidOid;
		stats->stanumbers[i] = value;
		stats->numnumbers[i] = 1;
	}

	stats->stats_valid = true;
}



PG_FUNCTION_INFO_V1(mytype_in);
Datum mytype_in(PG_FUNCTION_ARGS)
{
	char *num = PG_GETARG_CSTRING(0);
	int32 *numval;

	numval = (int32 *)palloc(sizeof(int32));
	sscanf(num, "%d", numval);
	
	PG_RETURN_POINTER(numval);
}


PG_FUNCTION_INFO_V1(mytype_out);
Datum mytype_out(PG_FUNCTION_ARGS)
{
	int32 *arg1 = (int32 *)PG_GETARG_POINTER(0);
	char *result = (char *) palloc(12);	/* sign, 10 digits, '\0' */

	sprintf(result, "%d", *arg1);
	PG_RETURN_CSTRING(result);
}


PG_FUNCTION_INFO_V1(mytype_analyze);
Datum mytype_analyze(PG_FUNCTION_ARGS)
{
	VacAttrStats *stats = (VacAttrStats *)PG_GETARG_POINTER(0);	

	/* Setup the minimum rows and the algorithm function */
	stats->minrows = 300 * stats->attr->attstattarget;
	stats->algfunc = compute_test_stats;

	/* Indicate we are done successfully */
	PG_RETURN_BOOL(true);
}
