I don't know if it's the proximate source of your problem but your
MemoryContextSwitchTo() calls are mixed up. You're reusing the same oldcontext
variable for both the switch you're doing in the main body and the switch
you're doing in the inner loop. At the very least you should use two different
oldcontext variables, currently I think you're leaving the memory context set
to the per_query_ctx.
But I think in this situation you're going to end up just doing the whole
thing in per_query_ctx anyways. The only part you can avoid that for is the
pallocing of the heap_form_tuple args and the actual heap_form_tuple call. The
tuple will be copied when you call tuplestore_puttuple (which should be done
in the same context the tuplestore was created in).
-- Gregory Stark EnterpriseDB http://www.enterprisedb.com Get trained by Bruce Momjian - ask me about
EnterpriseDB'sPostgreSQL training!