我正在尝试将以下SQL函数重写为c等效(尝试使其更快一点):
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;
我认为我可以修改现有的date
+ int4
运算符并执行以下操作:
#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);
}
如果我编译我的函数并将其转换为.so
我可以在PostgreSQL中创建dwd
函数:
create or replace function dwd(int) returns date as
'/usr/lib/postgresql/9.3/lib/dwd', 'dwd'
language c
cost 1;
2000-01-01
获得select dwd(0);
,但我期待2006-12-31
。显然DateADT dateVal = PG_GETARG_DATEADT(2006-12-31);
存在问题。
如何在此c函数中定义日期常量?
答案 0 :(得分:2)
现在它有效。事实证明DateADT
是自2000-01-01以来的天数(整数)。
c功能:
#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)
{
int32 days = PG_GETARG_INT32(0);
if (days > 0) {
DateADT dateVal = 2556;
PG_RETURN_DATEADT(dateVal + days);
}
else {
PG_RETURN_NULL();
}
}
性能测试:
drop table if exists tmp;
create table tmp as select dat2(gs) from generate_series(1,1000000) gs;
-- Query returned successfully: 1000000 rows affected, 4101 ms execution time.
drop table if exists tmp;
create table tmp as select dwd(gs) from generate_series(1,1000000) gs;
-- Query returned successfully: 1000000 rows affected, 1527 ms execution time.
在我的搜索过程中,我发现this对于PostgreSQL中的c函数非常有用。