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

标签 postgresql transactions with-statement

我在 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 语句仍算作单个语句,因此它将在隐式事务 block 中运行。

您可以使用一些返回当前事务 ID 的 CTE 自行测试:

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

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

关于postgresql - WITH 语句中的查询是否在 PostgreSQL 的单个事务中执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56932562/

相关文章:

python - 如何模拟在 with 语句中使用的 open (使用 Python 中的 Mock 框架)?

sql - Postgresql 转储是否创建以最后一个键开头或之后的序列?

python - 如何使用 sqlalchemy 将带有 datetime.timedelta 类型数据对象的 pandas 数据框存储到 postgresql d/b 中?

python - 提交后保持对数据库对象的锁定

python /SQLite3 : cannot commit - no transaction is active

sql - 是否可以回滚主要 SQL 数据库中的 CREATE TABLE 和 ALTER TABLE 语句?

java - Quartz调度程序产生 "ResultSet is closed"异常

postgresql - 简单的查找查询在 Postgres 上很慢,在 MySQL 上很快

python-3.x - python lock with-statement 和 timeout

python - `with` 语句 __enter__ 和 __exit__ 线程安全吗?