Database Reference
In-Depth Information
To make the example clearer, we provide a constant array of possible orderings to
be used when permuting the values.
Also, we read argument fields a , b , and c only once at the beginning of the function
and save the extracted values in a structure c_reverse_tuple_args , which we
allocate and initialize at the first call. For the structure to survive through all calls,
we allocate this structure in a special memory context which is maintained in the
funcctx -> multi_call_memory_ctx and store the pointer to this structure in
funcctx -> user_fctx . We also make use of funcctx fields: call_cntr and
max_calls .
In the same code section run once at the first call, we also prepare the descriptor
structure needed for returning the tuples. To do so, we fetch the return tuple
descriptor by passing the address we get in funcctx->tuple_desc to function
get_call_result_type(...) , and we complete the preparation by calling
BlessTuple(...) on it to fill in the missing bits needed for using it for returning
values.
At the end of this section, we restore the memory context. While you usually do not
need to pfree() the things you have palloc() allocated, you should always re-
member to restore the memory context when you are done using any context you
have switched to or else you risk messing up PostgreSQL in a way that can be hard
to debug later!
The rest is something that gets done at each call, including first one.
We start by checking that there is still something to do by comparing that current call
to the max calls parameter. This is by no means the only way to determine if we have
returned all values, but it is the simplest way if you know ahead how many rows you
are going to return. If there are no more rows to return, we signal this back using
SRF_RETURN_DONE() .
The rest is very similar to what the previous single-tuple function did. We compute
the retvals and retnulls arrays using the index permutations array ips and
then construct a tuple to return using heap_form_tuple(funcctx-
>tuple_desc, retvals, retnulls); .
Search WWH ::




Custom Search