Re: EXPLAIN ANALYZE CREATE TABLE AS EXECUTE runs non-SELECT prepared statements

From: Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>
To: Zsolt Parragi <zsolt(dot)parragi(at)percona(dot)com>
Cc: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: EXPLAIN ANALYZE CREATE TABLE AS EXECUTE runs non-SELECT prepared statements
Date: 2026-11-20 03:28:53
Message-ID: C0A6039D-4974-4FFA-9719-1B66E329561B@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

> On Nov 19, 2026, at 17:51, Zsolt Parragi <zsolt(dot)parragi(at)percona(dot)com> wrote:
>
> Hello
>
> CREATE TABLE AS EXECUTE only accepts a prepared SELECT, rejecting
> anything else with "prepared statement is not a SELECT". EXPLAIN
> ANALYZE doesn't have the same check, so it runs whatever the prepared
> statement is.
>
> This is another issue I found while working on EXPLAIN ANALYZE CTAS
> event triggers [1].
>
> Simple repro:
>
> CREATE TABLE src (a int);
> PREPARE ins AS INSERT INTO src VALUES (1) RETURNING *;
> CREATE TABLE t1 AS EXECUTE ins; -- ERROR: prepared statement is not a SELECT
> EXPLAIN ANALYZE CREATE TABLE t2 AS EXECUTE ins; -- inserts, creates t2
> with the RETURNING rows
>
> It seems clearly wrong, and the plain EXPLAIN variant also happily
> shows the plan of something CREATE TABLE AS would reject.

Agreed.

>
> The attached patch adds the same check to ExplainExecuteQuery. It goes
> back to 9dbf2b7d75d, and the fix is small enough to backpatch.
>
> [1]: https://postgr.es/m/CAN4CZFOycbakF5swg0i_hH2dZTkMP2%2BoA%3DnoU0VFFFe3687ojw%40mail.gmail.com
> <v1-0001-Reject-non-SELECT-prepared-statements-in-EXPLAIN-.patch>

V1 looks good to me.

I found something out of scope of this patch. When I tested this patch by copying your repro statements, my db happened to have a table named “t2” already, thus I got:
```
evantest=# EXPLAIN ANALYZE CREATE TABLE t2 AS EXECUTE ins;
ERROR: relation "t2" already exists
```

From user’s perspective, as EXPLAN doesn’t really create a table, the statement should more be reasonable to fail with "prepared statement is not a SELECT”.

Then digging further, I found that if the EXECUTE statement contains a volatile function, even if "prepared statement is not a SELECT” is raised, the volatile function has been executed, which also feels unreasonable.

Anything, those are different problems that should not block this patch.

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

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message shveta malik 2026-11-20 03:32:22 Re: Initial table sync copies the whole table when it is no longer published
Previous Message Chengpeng Yan 2026-11-20 03:05:03 Re: [PATCH] Fix encoding-dependent LIKE/regex selectivity estimates