I have created a function for age which receives an array as an argument and outputs all it's elements except the head of the list. But I wanted to add a second argument to output the N
last elements from the array. Although many age list functions retrieve the array as an agtype *agt_arg
, the functions which get the scalar argument uses the Datum *args
to retrieve the value. But using both the array and the scalar value as arguments, how should I proceed? Here is the function's PR

- 716
- 1
- 10
4 Answers
From my understanding you are using the count
variable to iterate through the list right? So lets se you want to take only the last 3 elements of the list and the length is 10. If you do count - n
you will get in this case 7, and then you can iterate from that index (e.g 7) until the end of the list.
At least thats what I understood correct me if Im wrong.

- 254
- 1
- 1
- 8
-
Yeah but I wanted the `n` to be part of the argument of the function so that the user can define how many elements from the tail of the list it is going to appear. Something like `age_tail([1,2,3,4,5], 2)` to show `[4, 5]`. But I don't know how to retrieve the second argument's integer value since it's being stored in an `agtype` data. – Matheus Farias Jul 07 '23 at 21:04
-
What if you take the second argument with `PG_GETARG_INTXX(1)`? I would assume that the input of the user would be an integer right? – Panagiotis Foliadis Jul 07 '23 at 21:23
-
`PG_GETARG_INTXX(1)` doesn't work – Matheus Farias Jul 07 '23 at 22:30
-
XX should be replaced by the value that you want for your `INT` like `32` or `64. Also you can try `AG_GET_ARG_AGTYPE_P(1)` , and maybe cast it to scalar after some checks – Panagiotis Foliadis Jul 08 '23 at 13:26
-
Yeah I did that, replaced with 64 and didn't work. – Matheus Farias Jul 10 '23 at 13:32
You can take help from the agtype_add
function in agtype_ops.c. For your case, what I can think of is that your function takes two agtype arguments and then retrieve the values as:
agtype *list = AG_GET_ARG_AGTYPE_P(0);
agtype *element = AG_GET_ARG_AGTYPE_P(1);
and then you can check whether the element
is a scalar or not.

- 728
- 1
- 2
- 8
Because age_tail
is a variadic function, you should use the appropriate function to extract its arguments which is extract_variadic_args
. This function also returns the types of the arguments which you can compare to AGTYPEOID
and INT4OID
to see if the first argument is agtype and second one is integer.
if (type == AGTYPEOID)
agt_arg = DATUM_GET_AGTYPE_P(arg);
if (type == INT4OID)
count = (int64)DatumGetInt32(arg);
See the implementation of any variadic function like age_toInteger
to have a better idea.

- 433
- 9
You can fetch the integer as the second argument with this:
int32 = PG_GETARG_INT32(1); // change 32 with the size of the int you need
Also don't forget to change the declaration in the age--1.3.0.sql file with the new argument to get recognized.

- 33
- 4