Add new for_each macros for iterating over a List that do not require ListCell pointer

From: Jelte Fennema <postgres(at)jeltef(dot)nl>
To: PostgreSQL-development <pgsql-hackers(at)postgresql(dot)org>
Subject: Add new for_each macros for iterating over a List that do not require ListCell pointer
Date: 2023-10-24 16:03:48
Message-ID: CAGECzQSwXKnxGwW1_Q5JE+8Ja20kyAbhBHO04vVrQsLcDciwXA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Many usages of the foreach macro in the Postgres codebase only use the
ListCell variable to then get its value. This adds macros that
simplify iteration code for that very common use case. Instead of
passing a ListCell you can pass a variable of the type of its
contents. This IMHO improves readability of the code by reducing the
total amount of code while also essentially forcing the use of useful
variable names.

While this might seem like a small quality of life improvement, in
practice it turns out to be very nice to use. At Microsoft we have
been using macros very similar to these ones in the Citus codebase for
a long time now and we pretty much never use plain foreach anymore for
new code.

Finally, I guess there needs to be some bikeshedding on the naming. In
the Citus codebase we call them foreach_xyz instead of the
for_each_xyz naming pattern that is used in this patchset. I'm not
sure what the current stance is on if foreach should be written with
or without an underscore between for and each. Currently pg_list.h
uses both.

P.S. Similar macros for forboth/forthree are also possible, but
require an exponential macro count handle all different possibilities,
which might not be worth the effort since forboth/forthree are used
much less often than foreach. In Citus we do have 3 forboth macros
that don't require ListCell for the most common cases (foreach_ptr,
foreach_ptr_oid, foreach_int_oid). But I did not want to clutter this
patchset with that discussion.

Attachment Content-Type Size
v1-0001-Add-macros-for-looping-through-a-list-without-nee.patch application/octet-stream 4.6 KB
v1-0002-Use-new-for_each_xyz-macros-in-a-few-places.patch application/octet-stream 7.3 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Alvaro Herrera 2023-10-24 16:04:13 Re: SLRU optimization - configurable buffer pool and partitioning the SLRU lock
Previous Message Tom Lane 2023-10-24 15:59:06 Re: Bug: RLS policy FOR SELECT is used to check new rows