我正在为PostgreSQL编写一个C聚合函数,目前我正在使用PG_GETARG_POINTER
,如下所示:
Datum my_transfunc(PG_FUNCTION_ARGS) {
mystype *trans_data = (mystype *) PG_GETARG_POINTER(0);
// Do some operations on trans_data pointer.
// That make trans_data's memory content change. Then
PG_RETURN_POINTER(trans_data);
}
我的代码有什么问题(内存,......)吗?
答案 0 :(得分:0)
backend/executor/nodeAgg.c
说:
We compute aggregate input expressions and run the transition functions
in a temporary econtext (aggstate->tmpcontext). This is reset at least
once per input tuple, so when the transvalue datatype is
pass-by-reference, we have to be careful to copy it into a longer-lived
memory context, and free the prior value to avoid memory leakage. We
store transvalues in another set of econtexts, aggstate->aggcontexts
(one per grouping set, see below), which are also used for the hashtable
structures in AGG_HASHED mode. These econtexts are rescanned, not just
reset, at group boundaries so that aggregate transition functions can
register shutdown callbacks via AggRegisterCallback.
由于复制过渡值,因此必须为Datum
(例如bytea
),以便copyDatum
可以正确复制。
由于您使用的是指针(可能在SQL中声明为internal
),因此应该没问题; internal
是按值传递的。
你必须确保你的mystype
被分配在一个内存上下文中,该上下文在整个语句中存活但后来被清除。