Thread: Question about error handling with UDF written in C
Hello, I am trying to create a UDF in C that returns multiple rows. I followed the examples in the contrib directory which does the following:
1 /* create a function context for cross-call persistence */
2 funcctx = SRF_FIRSTCALL_INIT();
3
4 /* switch to memory context appropriate for multiple function calls */
5 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
6
7 /* Prepare the inter call array for returning the data */
8 someVariable = palloc(size);
9
10 /* total number of tuples to be returned */
11 funcctx->max_calls = NUM_OUTPUT_VARIABLES;
12 funcctx->user_fctx = someVariable;
13
14 /* Build a tuple descriptor for our result type */
15 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
16 ereport(ERROR,
17 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
18 errmsg("function returning record called in context "
19 "that cannot accept type record")));
My question is that if we detect an error at line 15 and we get into the ereport code, would the memory allocated under multi_call_memory_ctx gets cleaned up properly? The document only states that the memory allocated under multi_call_memory_ctx will be cleaned up by SRF_RETURN_DONE, but what about error situations such as the above?
Thanks
Terry Chong <198back@gmail.com> writes: > My question is that if we detect an error at line 15 and we get into the > ereport code, would the memory allocated under multi_call_memory_ctx gets > cleaned up properly? Yes, it would. That's just the executor's query context, or maybe a subcontext thereof, so it'll go away when the query is abandoned. By and large, functions following ordinary coding conventions don't need to worry about resource cleanup on error. The exception would be if you were holding open file descriptors or some such that the core system didn't know about. regards, tom lane