psql: Fix CREATE SCHEMA scanning of nested routine bodies

Chao Li <li.evan.chao@gmail.com>

From: Chao Li <li.evan.chao@gmail.com>
To: Postgres hackers <pgsql-hackers@lists.postgresql.org>
Cc: Tom Lane <tgl@sss.pgh.pa.us>, Kirill Reshke <reshkekirill@gmail.com>, jian he <jian.universality@gmail.com>
Date: 2026-06-22T09:34:53Z
Lists: pgsql-hackers

Attachments

Hi,

While testing “[d51697484] Support more object types within CREATE SCHEMA”, I found an issue that seems to be a psql regression.

See this repro:
```
evantest=# CREATE SCHEMA s CREATE VIEW begin AS SELECT 1;
evantest-# end;
WARNING:  there is no transaction in progress
CREATE SCHEMA
COMMIT
```

After the first CREATE SCHEMA line, the prompt changed from =# to -#, meaning psql appeared to be treating the view name “begin" as the start of a BEGIN ... END block. After I typed “end;" on the second line, the server executed the first line properly, then executed the second line as “end;", producing the “no transaction” warning. So, although psql waited for “end;", it still sent two statements to the server. This suggests a psql bug.

I then went back to commit 404db8f9, the immediate parent of d51697484, and ran the same test:
```
evantest=# CREATE SCHEMA s CREATE VIEW begin AS SELECT 1;
CREATE SCHEMA
evantest=#
evantest=# select * from s.begin;
 ?column?
----------
        1
(1 row)
```

It created schema “s" and created a view named “begin" under “s". So this seems to confirm a psql regression introduced by d51697484.

Looking at psqlscan.l, d51697484 made BEGIN/END tracking apply to CREATE SCHEMA, which seems too broad. I think we should only track BEGIN ... END for CREATE SCHEMA after seeing CREATE [OR REPLACE] FUNCTION/PROCEDURE. Following this direction, I tried to make a fix.

I added some test cases, but I’m not sure whether 001_basic.pl is the right place for them. Should these tests be added to a new file, say 040_psqlscan.pl? I saw src/test/regress/sql/create_schema.sql, but I believe that is for server-side testing, so these client-side tests should not go there. Suggestions are appreciated.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/




Commits

  1. psql: Tighten heuristics for BEGIN/END within CREATE SCHEMA.

  2. Execute foreign key constraints in CREATE SCHEMA at the end.