Datum pg_theta_sketch_from_internal()

in src/theta_sketch_pg_functions.c [191:221]


Datum pg_theta_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, "theta_sketch_from_internal called in non-aggregate context");
  }
  oldcontext = MemoryContextSwitchTo(aggcontext);

  stateptr = (struct agg_state*) PG_GETARG_POINTER(0);
  if (stateptr->type == MUTABLE_SKETCH) {
    stateptr->ptr = theta_sketch_compact(stateptr->ptr);
  } else if (stateptr->type == UNION) {
    stateptr->ptr = theta_union_get_result(stateptr->ptr);
  } else if (stateptr->type == INTERSECTION) {
    stateptr->ptr = theta_intersection_get_result(stateptr->ptr);
  }
  bytes_out = theta_sketch_serialize(stateptr->ptr, VARHDRSZ);
  theta_sketch_delete(stateptr->ptr);
  pfree(stateptr);
  SET_VARSIZE(bytes_out.ptr, bytes_out.size);

  MemoryContextSwitchTo(oldcontext);

  PG_RETURN_BYTEA_P(bytes_out.ptr);
}