I’m creating a function for Apache AGE, and I need to iterate over a List
of graphids
, how should I do it properly?
- The
List
I’m referring to is the PostgreSQL defined struct in this file -> Postgres’ GitHub repository Link graphid
is just anint64
.
What I’m essentially trying to do is this:
graphid new_graphid = 0;
graphid vertex_to_connect = 0;
List* graphids_array = NIL;
(...)
for (int64 i=(int64)1;i<graph.graph_size;i++)
{
new_graphid = create_vertex(&graph);
graphids_array = lappend_int(graphids_array, new_graphid);
for(int64 j = 0; j<graphids_array->length-1; j++)
{
vertex_to_connect = list_nth_int(graphids_array, j);
connect_vertexes_by_graphid(&graph,
new_graphid,
vertex_to_connect);
}
}
(...)
The problem happening is that the vertex_to_connect
variable is not receiving the proper graphid
(which should be a big number like 844424930131970), instead, it’s getting small values that seems to be from the j
variable.
Any help on showing where I could be mistaken is appreciated.
2
Answers
It looks like youre using the list_nth_int() function to get vertex_to_connect value from graphids_array. But list_nth_int() function gets an element from list by its position instead of its value. As a result you’re getting small values that vertex_to_connect gets small values that seem like they belong to j variable, because j is the index of the list element, not the actual value of the element.
In order to iterate through a
List
you can use theforeach
loop with aListCell
iterator. Here is an example of how you can do this:Alternatively, you could use the
ListGraphId
structure to create your list. Since it’s onlygraphid
s, I believe it will do the trick. Then, you would need to create an iterator to peek at each element of the list as aGraphIdNode
. I believe it would be necessary to create afor
orwhile
loop for this, but then update at the end of the loop for the iterator to be the next value of theGraphIdNode
. So, something like this would traverse the entire list:You can find more about it at
src/backend/utils/adt/age_graphid_ds.c
andsrc/include/utils/age_grapid_ds.h
.https://github.com/apache/age/blob/master/src/backend/utils/adt/age_graphid_ds.c