You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@age.apache.org by VUONG QUOC Viet <vq...@bitnine.net> on 2021/10/01 15:22:04 UTC

On reverse() function

HI everyone,
While working on writing reverse(), I have a few questions that I hope you
guys can confirm the answer to make sure I'm heading in the right direction.
The function I'm writing takes a list, and returns a reverse list. However,
I should declare the function to take an agtype and return an agtype,
shouldn't I?

CREATE FUNCTION ag_catalog.reverse(agtype)
RETURNS agtype
LANGUAGE c
STABLE
RETURNS NULL ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';

The use of the reverse function will be like this:
WITH [4923, 'abc', 521, NULL, 487] AS ids
RETURN reverse(ids)

Therefore, I run the query:

WITH [4923, 'abc', 521, NULL, 487] AS ids
RETURN ids

, and trace the code. It resolves to the function agtype_build_list, which
is the following:

Datum agtype_build_list(PG_FUNCTION_ARGS)
{
int nargs;
int i;
agtype_in_state result;
Datum *args;
bool *nulls;
Oid *types;

/*build argument values to build the array */
nargs = extract_variadic_args(fcinfo, 0, true, &args, &types, &nulls);

if (nargs < 0)
PG_RETURN_NULL();

memset(&result, 0, sizeof(agtype_in_state));

result.res = push_agtype_value(&result.parse_state, WAGT_BEGIN_ARRAY,
NULL);

for (i = 0; i < nargs; i++)
add_agtype(args[i], nulls[i], &result, types[i], false);

result.res = push_agtype_value(&result.parse_state, WAGT_END_ARRAY, NULL);

PG_RETURN_POINTER(agtype_value_to_agtype(result.res));
}

I played around with that function, tried replacing the line  for (i = 0; i
< nargs; i++)  as:
for (i = nargs-1; i >= 0 ; i++)
, then the list is reversed.
So I somehow know how to reverse the list. It's just the way to write a
function that I need to find out.
Best regards,
Viet.