I am trying to rewrite the following SQL function into c equivalent (trying to make it a little bit faster):
CREATE OR REPLACE FUNCTION dat2(time_key integer)
RETURNS date AS
$BODY$
BEGIN
RETURN case when time_key > 0 then '2006-12-31'::date + time_key end as result;
END;
$BODY$
LANGUAGE plpgsql IMMUTABLE STRICT
COST 100;
I thought I can modify existing date+int4 operator and do something like:
#include "postgres.h"
#include "fmgr.h"
#include "utils/date.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
PG_FUNCTION_INFO_V1(dwd);
Datum
dwd(PG_FUNCTION_ARGS)
{
/* DateADT dateVal = PG_GETARG_DATEADT(0); */
DateADT dateVal = PG_GETARG_DATEADT(2006-12-31);
int32 days = PG_GETARG_INT32(0);
PG_RETURN_DATEADT(dateVal + days);
}
If I compile my function and turn it into .so I can create dwd function in PostgreSQL:
create or replace function dwd(int) returns date as
'/usr/lib/postgresql/9.3/lib/dwd', 'dwd'
language c
cost 1;
I get 2000-01-01 for select dwd(0);, but I expected 2006-12-31. Apparently there is problem in DateADT dateVal = PG_GETARG_DATEADT(2006-12-31);.
How do I define date constant in this c function?
dwdis three-times faster then SQL functiondat2, see my answer.dat2is (say) 2% of execution cost, you haven't gained much. That's what I was saying: Worth profiling first, to see whether what you're looking at optimizing is actually worth improving.