DEV Community

Marco Aurélio Silva de Souza Júnior
Marco Aurélio Silva de Souza Júnior

Posted on

Source code tour on Apache AGE & Postgres - Lists

Introduction

In PostgreSQL, the ListCell struct is a key component for implementing linked lists, which we will use frequently on our contribution to Apache AGE. You can check its implementation in PostgreSQL's official GitHub Repository.

This blog post provides a concise overview of the ListCell struct, its purpose, and significance, along with an example of iterating over a List using ListCell.

The ListCell Struct:

The ListCell struct, defined in pg_list.h, has two members:

  • next: a pointer to the next ListCell in the linked list, enabling traversal.
  • data: a void pointer to store the actual data in each ListCell.

Iterating over a List using ListCell:

Let's consider an example of iterating over a list using ListCell. Assume we have a List of integers, and we want to print each element:

List *myList; // Assume we have a List containing integers

ListCell *cell;
foreach(cell, myList)
{
    int *value = (int *) lfirst(cell);
    printf("%d\n", *value);
}
Enter fullscreen mode Exit fullscreen mode

In this example, we declare a ListCell pointer cell and use the foreach macro provided by PostgreSQL to iterate over the myList. Within the loop, we extract the integer value stored in each ListCell using lfirst, which returns a void pointer. We then cast it to an int pointer and dereference it to obtain the actual value, which we print.


The ListCell struct is a vital component of PostgreSQL's linked list implementation. It facilitates the creation and manipulation of dynamic lists throughout the PostgreSQL source code, showcasing the system's flexibility and versatility. By utilizing ListCell and its associated macros, such as foreach, iterating over lists becomes straightforward and efficient.

Please note that this condensed blog post provides a high-level overview of the ListCell struct and an example of iteration. For more detailed information, refer to the official PostgreSQL documentation and source code.


Top comments (0)