-- statmath.sql
--
-- Install the statistical aggregates
--

--
-- Create the new data type for the state transition variable
--
CREATE FUNCTION statmath_stateval_in(opaque)
	RETURNS statmath_stateval
	AS 'MODULE_PATHNAME'
	LANGUAGE 'C';

CREATE FUNCTION statmath_stateval_out(opaque)
	RETURNS opaque
	AS 'MODULE_PATHNAME'
	LANGUAGE 'C';

CREATE TYPE statmath_stateval (
	internallength = 16,
	input = statmath_stateval_in,
	output = statmath_stateval_out,
	alignment = double
);

--
-- Create the statistic data collector used in the aggregates
--
CREATE FUNCTION statmath_collect(statmath_stateval, float8)
	RETURNS statmath_stateval
	AS 'MODULE_PATHNAME'
	LANGUAGE 'C';

--
-- Create the final functions for the three aggregates
--
CREATE FUNCTION statmath_average_fin(float8, int4)
	RETURNS float8
	AS 'MODULE_PATHNAME'
	LANGUAGE 'C';

CREATE FUNCTION statmath_variance_fin(statmath_stateval, int4)
	RETURNS float8
	AS 'MODULE_PATHNAME'
	LANGUAGE 'C';

CREATE FUNCTION statmath_stddev_fin(statmath_stateval, int4)
	RETURNS float8
	AS 'MODULE_PATHNAME'
	LANGUAGE 'C';

--
-- Create the aggregates themself
--
CREATE AGGREGATE average (
	basetype = float8,
	stype1 = float8,
	stype2 = int4,
	sfunc1 = float8pl,
	sfunc2 = int4inc,
	finalfunc = statmath_average_fin,
	initcond1 = '0',
	initcond2 = '0'
);

CREATE AGGREGATE variance (
	basetype = float8,
	stype1 = statmath_stateval,
	stype2 = int4,
	sfunc1 = statmath_collect,
	sfunc2 = int4inc,
	finalfunc = statmath_variance_fin,
	initcond1 = '0:0',
	initcond2 = '0'
);

CREATE AGGREGATE stddev (
	basetype = float8,
	stype1 = statmath_stateval,
	stype2 = int4,
	sfunc1 = statmath_collect,
	sfunc2 = int4inc,
	finalfunc = statmath_stddev_fin,
	initcond1 = '0:0',
	initcond2 = '0'
);


