Re: plpgsql FOR loop doesn't guard against strange step values

From: Andrew Dunstan <andrew(at)dunslane(dot)net>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Peter Eisentraut <peter_e(at)gmx(dot)net>, pgsql-hackers(at)postgresql(dot)org
Subject: Re: plpgsql FOR loop doesn't guard against strange step values
Date: 2007-07-14 23:07:15
Message-ID: 46995723.1000800@dunslane.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Tom Lane wrote:
> Peter Eisentraut <peter_e(at)gmx(dot)net> writes:
>
>> Tom Lane wrote:
>>
>>> I just noticed that when the BY option was added to plpgsql FOR
>>> loops, no real error checking was done. If you specify a zero step
>>> value, you'll have an infinite loop. If you specify a negative
>>> value, the loop variable will increment in the "wrong direction"
>>> until integer overflow occurs. Neither of these behaviors seem
>>> desirable in the least.
>>>
>
>
>> That seems to be fairly normal proramming language behavior.
>>
>
> Well, it's about what I'd expect from C or something at a similar level
> of (non) abstraction. But I dislike the idea that plpgsql should have
> behavior as machine-dependent as that the number of iterations will
> depend on the value of INT_MIN. Also, at the SQL level our usual policy
> is to throw errors for obvious programmer mistakes, and it's hard to
> argue that a zero or negative step isn't a programmer mistake. Had we
> defined the stepping behavior differently (ie, make "BY -1" work like
> REVERSE) then there would be some sanity in allowing negative steps,
> but I don't see the sanity in it given the implemented behavior.
>

I suspect we have a significant incompatibility with PLSQL in this area.
The docs give this example:

FOR i IN REVERSE 10..1 LOOP
-- some computations here
END LOOP;

In PLSQL, as I understand it, (and certainly in its ancestor Ada) this loop will execute 0 times, not 10. To iterate from 10 down to 1 one would need to say:

FOR i IN REVERSE 1..10 LOOP
-- some computations here
END LOOP;

I'm not sure if this has been noticed before. It's actually quite unfortunate. At least it should be mentioned in the section of the docs relating to porting from PLSQL.

cheers

andrew

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 2007-07-14 23:10:34 Re: plpgsql and qualified variable names
Previous Message Heikki Linnakangas 2007-07-14 21:44:32 Re: plpgsql and qualified variable names