Re: « The PL/pgSQL interpreter parses the function's source text and produces an internal binary instruction tree... » - Mailing list pgsql-general

From Christophe Pettus
Subject Re: « The PL/pgSQL interpreter parses the function's source text and produces an internal binary instruction tree... »
Date
Msg-id 445B2142-D857-4BD4-9DA9-3988D6CF5658@thebuild.com
Whole thread Raw
In response to Re: « The PL/pgSQL interpreter parses the function's source text and produces an internal binary instruction tree... »  (Bryn Llewellyn <bryn@yugabyte.com>)
Responses Re: « The PL/pgSQL interpreter parses the function's source text and produces an internal binary instruction tree... »  (Bryn Llewellyn <bryn@yugabyte.com>)
List pgsql-general

> On Jul 28, 2022, at 18:49, Bryn Llewellyn <bryn@yugabyte.com> wrote:
> It's this that surprises me. And it's this, and only this, that I'm asking about: might _just_ this be a fixable bug?

It might be surprising, but it's not a bug.  You can demonstrate it with a very small test case:

CREATE FUNCTION f() RETURNS VOID AS $$
DECLARE
   x int not null := 0;
BEGIN
   x := y;
END;
$$ language plpgsql;

But gets an error on execution:

xof=# SELECT f();
ERROR:  column "y" does not exist
LINE 1: x := y
             ^
QUERY:  x := y
CONTEXT:  PL/pgSQL function f() line 5 at assignment

The clue is that it is complaining about a missing "column."  Assignment in PL/pgSQL is essentially syntactic sugar
arounda SELECT ... INTO.  The assignment there is processed pretty much as if it were written: 

    SELECT y INTO x;

Note, however, that this does *not* compile:

CREATE OR REPLACE FUNCTION f() RETURNS VOID AS $$
DECLARE
   x int not null := 0;
BEGIN
   y := x;
END;
$$ language plpgsql;

ERROR:  "y" is not a known variable
LINE 5:    y := x;

Unquestionably, this is surprising!  The reasons, such as they are, are based in how PL/pgSQL processes SQL statements.
(For example, if you look at the grammar, it literally takes "SELECT x INTO y;" turns it into "SELECT x       ;", and
passesthat to the SPI.  This has the virtue that it doesn't have to have a complete PostgreSQL SQL grammar replicated
init (what a nightmare), but it does result in some of the implementation poking through. 


pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: Re: « The PL/pgSQL interpreter parses the function's source text and produces an internal binary instruction tree... »
Next
From: Bryn Llewellyn
Date:
Subject: Re: « The PL/pgSQL interpreter parses the function's source text and produces an internal binary instruction tree... »