在交易中获取TransActionID

发布于 2025-01-27 12:51:03 字数 427 浏览 1 评论 0原文

我正在尝试从pg_locks表中获取TransActionId当Aquired Postgres Advisory Lock in Dressaction内部表,但它始终是null。我想确保锁定的Aquired Witin交易。有办法做到吗?

BEGIN TRANSACTION;

SELECT pg_try_advisory_xact_lock(4);

SELECT transactionid
FROM pg_locks
WHERE locktype = 'advisory'
AND objid = 4;

Postgres容器:Postgres:13.4-Alpine

I'm trying to get transactionid from pg_locks table when aquired Postgres advisory lock within transaction, but it's always NULL. I want to be sure that lock aquired witin transaction. Is there is a way to do it?

BEGIN TRANSACTION;

SELECT pg_try_advisory_xact_lock(4);

SELECT transactionid
FROM pg_locks
WHERE locktype = 'advisory'
AND objid = 4;

Postgres container: postgres:13.4-alpine

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

十雾 2025-02-03 12:51:03

当您获得锁定时,交易尚未持有永久ID,您可以看到:

BEGIN TRANSACTION;

SELECT pg_try_advisory_xact_lock(4);

SELECT *
FROM pg_locks;

锁定交易ID列表中没有锁定。

从文档:

每笔交易在整个持续时间内都有其虚拟交易ID的独家锁定。如果将永久ID分配给事务(通常仅在交易更改数据库状态时发生),则它还在其永久交易ID上包含一个独家锁,直到结束为止。

您可以尝试通过PID搜索所需的锁:

SELECT * FROM pg_locks WHERE pid = pg_backend_pid() AND locktype = 'advisory';

When you get a lock, your transaction is not yet holding a permanent id, you can see this:

BEGIN TRANSACTION;

SELECT pg_try_advisory_xact_lock(4);

SELECT *
FROM pg_locks;

There is no lock on hold in the list of locks transaction id.

From the doc:

Every transaction holds an exclusive lock on its virtual transaction ID for its entire duration. If a permanent ID is assigned to the transaction (which normally happens only if the transaction changes the state of the database), it also holds an exclusive lock on its permanent transaction ID until it ends.

You can try to search for the locks you need by pid:

SELECT * FROM pg_locks WHERE pid = pg_backend_pid() AND locktype = 'advisory';
祁梦 2025-02-03 12:51:03

doc on pg_locks SADE :

transactionId xid

锁定的交易的ID,如果目标为null,则为null
不是交易ID

换句话说,

pg_locks.transactionIdlocktype ='TransActionId'时填充在当时。检查获取锁定的正常方法是测试pg_try_advisory_xact_lock的返回值。

要在查找pg_locks的事实之后进行测试,您可以使用当前后端获得的事实:

SELECT 1
FROM pg_locks
WHERE locktype = 'advisory'
AND pid = pg_backend_pid()
AND objid = 4;

The doc on pg_locks says:

transactionid xid

ID of the transaction targeted by the lock, or null if the target is
not a transaction ID

In other words, pg_locks.transactionid is filled in when locktype='transactionid'.

The normal way to check if the lock is acquired is to test the return value of pg_try_advisory_xact_lock.

To test it after the fact looking up pg_locks, you could use the fact that it has been acquired by the current backend:

SELECT 1
FROM pg_locks
WHERE locktype = 'advisory'
AND pid = pg_backend_pid()
AND objid = 4;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文