如何检查 PostgreSQL 事务中的挂起操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1651219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:22:32  来源:igfitidea点击:

How to check for pending operations in a PostgreSQL transaction

postgresqltransactionssqlalchemy

提问by Gunnlaugur Briem

I have a session (SQLAlchemy) on PostgreSQL, with an active uncommitted transaction. I have just passed the session to some call tree that may or may not have issued SQL INSERT/UPDATE/DELETEstatements, through sqlalchemy.ormor directly through the underlying connection.

我在 PostgreSQL 上有一个会话 (SQLAlchemy),有一个活动的未提交事务。我刚刚通过了会议,可能会或可能不会发出SQL一些调用树INSERT/ UPDATE/DELETE语句,通过sqlalchemy.orm或直接通过底层连接。

Is there a way to check whether there are any pending data-modifying statements in this transaction? I.e. whether commit would be a no-op or not, and whether rollback would discard something or not?

有没有办法检查这个事务中是否有任何未决的数据修改语句?即提交是否为空操作,回滚是否会丢弃某些内容?

I've seen people point out v$transactionin Oracle for the same thing (see this SO question). I'm looking for something similar to use on PostgreSQL.

我已经看到人们v$transaction在 Oracle 中指出了同样的事情(参见这个 SO 问题)。我正在寻找类似于在 PostgreSQL 上使用的东西。

采纳答案by Kuberchaun

回答by shaunc

Consider the following sequence of statements:

考虑以下语句序列:

select txid_current();

begin;

select txid_current();

If the transaction id returned by the two selects is equal, then there is an open transaction. If not then there wasn't, (but now is).

如果两次 select 返回的事务 id 相等,那么就有一个打开的事务。如果没有,那么就没有,(但现在是)。

If the numbers are different, then as a side effect you will just have opened a transaction, which you will probably want to close.

如果数字不同,那么作为副作用,您将刚刚打开一个交易,您可能想要关闭该交易。

UPDATE: In fact, as @r2evans points out (thanks for the insight!), you don't need the "begin" -- txid_current() will return the same number just if you are in a transaction.

更新:事实上,正如@r2evans 指出的(感谢您的洞察力!),您不需要“开始”—— txid_current() 将返回相同的数字,如果您在交易中。

回答by Magnus Hagander

No, not from the database level, really. Perhaps you can add some tracing at the sqlalchemy level to track it?

不,不是从数据库级别,真的。也许您可以在 sqlalchemy 级别添加一些跟踪来跟踪它?

Also, how do you define a no-op? What if you updated a value to the same value it had before, is that a no-op or not? From the databases perspective, if it had one, it would not be a no-op. But from the application perspective, it probably would.

另外,你如何定义无操作?如果您将一个值更新为与之前相同的值,这是否为空操作?从数据库的角度来看,如果它有一个,它就不会是一个空操作。但从应用程序的角度来看,它可能会。