BUG: PL/pgSQL FOREACH misparses variable named "slice" with SLICE clause - Mailing list pgsql-bugs

From Leendert Gravendeel
Subject BUG: PL/pgSQL FOREACH misparses variable named "slice" with SLICE clause
Date
Msg-id CA+i9DRE8Uh_rYTcbMvQBWCmjQNgb_4N=7V2vMPOZa1iQV7HOkA@mail.gmail.com
Whole thread
Responses Re: BUG: PL/pgSQL FOREACH misparses variable named "slice" with SLICE clause
Re: BUG: PL/pgSQL FOREACH misparses variable named "slice" with SLICE clause
List pgsql-bugs
Hello,

I believe I have found a parser issue in PL/pgSQL involving the
FOREACH ... SLICE syntax.

Version:
PostgreSQL 18 (reproduced on current release)

Description:
When using FOREACH with the SLICE clause, a loop variable named
`slice` is misinterpreted as the SLICE keyword, causing the statement
to fail. Renaming the variable to anything else makes the function
work as expected.

Reproduction:

  CREATE FUNCTION test_slice_conflict() RETURNS text
  LANGUAGE plpgsql AS $$
  DECLARE
    slice integer[];
    arr integer[] := ARRAY[[1,2],[3,4]];
  BEGIN
    FOREACH slice SLICE 1 IN ARRAY arr LOOP
    END LOOP;
    RETURN 'ok';
  END;
  $$;

Observed behavior:
The function fails to compile due to incorrect parsing of `slice`
as the SLICE keyword.

Expected behavior:
`slice` should be treated as a normal identifier (loop variable),
and the function should compile and run successfully.

Additional notes:
- Renaming the variable (e.g. to `abc`) makes the function work.
- This suggests a keyword/identifier ambiguity where the parser
  prefers the SLICE keyword in this context.

Given that the documentation describes the FOREACH target as a
regular variable, this behavior seems unintended.

Please let me know if additional information is needed.

Best regards,
Leendert Gravendeel



pgsql-bugs by date:

Previous
From: Daniel Schreiber
Date:
Subject: PostgreSQL 17: Bug in libpq when libpq is dlopened/closed multiple times
Next
From: Masahiko Sawada
Date:
Subject: Re: TRAP: failed Assert("offsets[i] > offsets[i - 1]"), File: "tidstore.c"