WITH 语句中的查询是否在 PostgreSQL 的单个事务中执行?

Are queries in the WITH statement executed in a single transaction in PostgreSQL?

我在 WITH 语句中做了很多查询。他们应该在一个事务中。我应该在事务中显式地覆盖我的大查询还是没有必要?

这是我的查询的粗略示例:

WITH
    remains_actual AS (
        SELECT
            ...
    )
    affected_remains AS (
        INSERT INTO
            ...
        ON CONFLICT (...) DO UPDATE SET
            ...
        RETURNING
            ...
    )
    affected_products AS (
        SELECT DISTINCT
            ...
    )
INSERT INTO
    ....

来自docs

PostgreSQL actually treats every SQL statement as being executed within a transaction. If you do not issue a BEGIN command, then each individual statement has an implicit BEGIN and (if successful) COMMIT wrapped around it.

WITH 语句仍然算作单个语句,因此在隐式事务块中它将是 运行。

您可以使用一些 CTE 自行测试,return 当前交易 ID:

with
  tx1 as (select txid_current()),
  tx2 as (select txid_current())
select * from tx1, tx2;

 txid_current | txid_current
--------------+--------------
        12814 |        12814
(1 row)