"Mark Cave-Ayland" <m.cave-ayland@webbased.co.uk> writes:
> My current code works by using MemoryContextCreate() to create a child
> context to MessageContext and using the Init()/Delete() functions to
> initialise and destroy a cache in the local backend. However, this doesn't
> really work particularly well when using cursors and prepared queries since
> it appears what I should be doing is using a cache per portal rather than a
> cache per backend.
If you want per-query state, keep it in a data structure linked from the
fcinfo->flinfo->fn_extra field (physically, store it in
fcinfo->flinfo->fn_mcxt, or create a subcontext of that if you wish).
If you need to get control at query shutdown to free non-palloc'd
resources, RegisterExprContextCallback may help. (I think such
callbacks are only called during *successful* query shutdown, though,
so if you have external library state you need to clean up anyway,
you'll need some other approach to keeping track of it ... maybe a
permanent data structure instead of a per-query one.)
src/backend/utils/fmgr/funcapi.c and src/backend/executor/functions.c
might be useful examples.
regards, tom lane