Re: BUG #17805: Unexpected results when bounds of FOR loop use non-integer numbers

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: jiangshan(dot)liu(at)tju(dot)edu(dot)cn, pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: BUG #17805: Unexpected results when bounds of FOR loop use non-integer numbers
Date: 2023-02-22 15:01:35
Message-ID: CAKFQuwaMFs8SFYpM42pqfD_YY7cyQpwp9OueD+YGTxj4vxN+VA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

On Wed, Feb 22, 2023 at 7:46 AM PG Bug reporting form <
noreply(at)postgresql(dot)org> wrote:

> The following bug has been logged on the website:
>
> Bug reference: 17805
> Logged by: Jiangshan Liu
> Email address: jiangshan(dot)liu(at)tju(dot)edu(dot)cn
> PostgreSQL version: 15.2
> Operating system: Ubuntu 18.04
> Description:
>
> I got unexpected results when I ran this PL/pgSQL function:
>
> CREATE FUNCTION test() RETURNS void AS $$
> BEGIN
> FOR i IN 1 .. 0.5*5 LOOP
> raise notice '%', i;
> END LOOP;
> END;
> $$ LANGUAGE plpgsql;
> SELECT * FROM test();
>
> The result of the execution is:
> NOTICE: 1
> NOTICE: 2
> NOTICE: 3
>
> I think this result is unexpected because the last round of loop variable
> is
> beyond the specified upper bound of the loop. Is this a bug in a FOR loop?
>

No, a loop needs a discrete data type so that a step makes sense. So
integer it is.

postgres=# select 2.5::integer;
int4
------
3
(1 row)

> But this seems to cause incomprehensible results. If it is unsafe to take
> values outside the upper and lower bounds of the loop, then this will lead
> to unintended consequences.

That is the nature of programming. Test your code and don't write stuff
that doesn't actually make sense.

> Is this implicit type conversion necessary? I
> think there are two better ways to do it.
> One is to report errors directly to the user.

In retrospect this probably would have been a better outcome. Introducing
an error/change now seems problematic though.

So, yes, if either bound is not an integer the value will be coerced to
become an integer by the normal casting rules between those types.

David J.

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message Alessandro Papa - Infolab 2023-02-22 16:17:47 pg_dump: error
Previous Message Justin Pryzby 2023-02-22 14:53:41 Re: Unlimited memory consumption with long-lived connection