proposal: FOREACH-IN-ARRAY (probably for 9.2?)

Pavel Stehule <pavel.stehule@gmail.com>

From: Pavel Stehule <pavel.stehule@gmail.com>
To: PostgreSQL Hackers <pgsql-hackers@postgresql.org>
Cc: Tom Lane <tgl@sss.pgh.pa.us>, Robert Haas <robertmhaas@gmail.com>
Date: 2010-12-16T19:19:17Z
Lists: pgsql-hackers

Attachments

Hello

I am resending a redesigned proposal about special plpgsql statement
that support iteration over an array.

The most conflict issue of last proposal was a syntax. It enhanced
relative complex FOR statement. So now, it's based on new statement
with simple syntax. We can use a keyword FOREACH, this isn't in
conflict with PL/SQL - use a keyword FORALL and it isn't in conflict
with SQL/PSM too. More - this special statement can be used for
PostgreSQL's specific purposes. It can carry a new features in future.
The design of proposed functionality is simple, but respects a
possibility for enhancing a FOREACH cycle for future.

==proposed syntax:==

[ <<label>> ]
FOREACH var [, var [..]] IN ARRAY expr
LOOP
  ...
END LOOP [ label ]

==the goals:==
  * cleaner syntax for full iteration over array
  * reduce a overhead from only seq. access to any field in array
(it's not too significant)
  * simplify iteration over multidimensional arrays

The most performance issue of access to a untoasted  array is "solved"
with other patch.

== Iteration over multidimensional arrays ==
Its designed to reduce one dimension from source array. It can remove
a slicing and simplify code:

CREATE OR REPLACE FUNCTION public.fa(anyarray)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE i int[];
BEGIN
  FOREACH i IN ARRAY $1
  LOOP
   RAISE NOTICE '%', i;
  END LOOP;
END;
$function$

postgres=# select fa(array[[[1,2],[3,4]],[[1,2],[3,4]],[[5,6],[7,8]]]);
NOTICE:  {{1,2},{3,4}}
NOTICE:  {{1,2},{3,4}}
NOTICE:  {{5,6},{7,8}}
 fa
----

(1 row)

postgres=# select fa(array[[1,2,3,4],[1,2,3,4],[5,6,7,8]]);
NOTICE:  {1,2,3,4}
NOTICE:  {1,2,3,4}
NOTICE:  {5,6,7,8}
 fa
----

(1 row)

ideas, notes?

Regards

Pavel