Datum pg_frequent_strings_sketch_build_agg()

in src/frequent_strings_sketch_pg_functions.c [53:90]


Datum pg_frequent_strings_sketch_build_agg(PG_FUNCTION_ARGS) {
  void* sketchptr;
  unsigned lg_k;
  const VarChar* str;
  unsigned long long weight;

  MemoryContext oldcontext;
  MemoryContext aggcontext;

  if (PG_ARGISNULL(0) && PG_ARGISNULL(2)) {
    PG_RETURN_NULL();
  } else if (PG_ARGISNULL(2)) {
    PG_RETURN_POINTER(PG_GETARG_POINTER(0)); // no update value. return unmodified state
  }

  if (!AggCheckCallContext(fcinfo, &aggcontext)) {
    elog(ERROR, "frequent_strings_sketch_build_agg called in non-aggregate context");
  }
  oldcontext = MemoryContextSwitchTo(aggcontext);

  if (PG_ARGISNULL(0)) {
    lg_k = PG_GETARG_INT32(1);
    sketchptr = frequent_strings_sketch_new(lg_k);
  } else {
    sketchptr = PG_GETARG_POINTER(0);
  }

  str = PG_GETARG_VARCHAR_P(2);

  // optional weight
  weight = PG_NARGS() > 3 ? PG_GETARG_INT64(3) : 1;

  frequent_strings_sketch_update(sketchptr, VARDATA(str), VARSIZE(str) - VARHDRSZ, weight);

  MemoryContextSwitchTo(oldcontext);

  PG_RETURN_POINTER(sketchptr);
}