in src/cpc_sketch_pg_functions.c [148:174]
Datum pg_cpc_sketch_from_internal(PG_FUNCTION_ARGS) {
struct agg_state* stateptr;
struct ptr_with_size bytes_out;
MemoryContext oldcontext;
MemoryContext aggcontext;
if (PG_ARGISNULL(0)) PG_RETURN_NULL();
if (!AggCheckCallContext(fcinfo, &aggcontext)) {
elog(ERROR, "cpc_sketch_from_internal called in non-aggregate context");
}
oldcontext = MemoryContextSwitchTo(aggcontext);
stateptr = (struct agg_state*) PG_GETARG_POINTER(0);
if (stateptr->type == UNION) {
stateptr->ptr = cpc_union_get_result(stateptr->ptr);
}
bytes_out = cpc_sketch_serialize(stateptr->ptr, VARHDRSZ);
cpc_sketch_delete(stateptr->ptr);
pfree(stateptr);
SET_VARSIZE(bytes_out.ptr, bytes_out.size);
MemoryContextSwitchTo(oldcontext);
PG_RETURN_BYTEA_P(bytes_out.ptr);
}