postgresql - PostgreSQL 事务 id (xmin) 是否按顺序出现在提交的版本中?

标签 postgresql transactions mvcc

由于 PostgreSQL 文档 https://www.postgresql.org/docs/current/ddl-system-columns.html

xmin The identity (transaction ID) of the inserting transaction for this row version (A row version is an individual state of a row; each update of a row creates a new row version for the same logical row).

我们正在使用它(不要问为什么,只是碰巧)用于同步数据并从 PostgreSQL 源数据库中提取(ETL 中的 E)更改,我们通过间隔扫描来实现它,特别是 xmin 间隔,例如我们已经同步xmin 间隔从 0 到 10002,在这种情况下,当我们进行下一次同步时,我们将从 10003 开始​​搜索 xmin。如果每个提交和可见的事务都按顺序编号,没有问题,所有数据更改都会按顺序编号,但是如果事务在初始化的那一刻就被编号,可能会发生下一种情况:

  • 事务 10001 于 15:01 开始
  • 事务 10002 于 15:02 开始
  • 事务 10002 在 15:02 提交
  • 事务 10001 在 15:03 提交

如果我们在 15:02 进行了同步,并且在目标数据库中获得了最大 xmin:10002,在这种情况下,在从 xmin 10003 开始​​的下一次同步中,我们将跳过 xmin 10001 并且将丢失更改。

那么 PostgreSQL 事务 id (xmin) 是否按顺序出现在提交的版本中?


同样的文档中也有xmax:

xmax The identity (transaction ID) of the deleting transaction, or zero for an undeleted row version. It is possible for this column to be nonzero in a visible row version. That usually indicates that the deleting transaction hasn't committed yet, or that an attempted deletion was rolled back.

所以我们可以看到计划删除行的事务(如果它将被提交),那么也许 xmin 也显示了将更改行的事务?但由于 xmin 的描述,这是不可能的:

...for this row version. (A row version is an individual state of a row; each update of a row creates a new row version for the same logical row.)

因为,如所写,它必须与我们读取的行版本相匹配,也许只能用脏读(当我们看到未提交的数据时),但这在 PostgreSQL 中不会发生 https://www.postgresql.org/docs/current/transaction-iso.html

Dirty Read: Allowed, but not in PG

最佳答案

在写这个问题的过程中,我找到了这张幻灯片:https://momjian.us/main/writings/pgsql/mvcc.pdf并且由于它的“MVCC 快照时间轴”部分,我认为 xmin 在快照中的出现可能不是顺序的。

但我在这里找到了解决方案:https://www.postgresql.org/docs/9.6/functions-info.html#FUNCTIONS-TXID-SNAPSHOT

txid_snapshot_xip(txid_snapshot) [setof bigint] get in-progress transaction IDs in snapshot

所以我可以获得一组尚未提交的事务,并检查它们是否包含小于关闭当前同步进程间隔的最大 xid 的 xid,如果包含则需要等待一段时间,然后再次检查并继续如果同步间隔内的所有事务都已完成,则提取数据,否则错误退出进程。

关于postgresql - PostgreSQL 事务 id (xmin) 是否按顺序出现在提交的版本中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60189514/

相关文章:

postgresql - 用于具有大量更新的长时间运行事务的数据库

postgresql - 如何对接MongoDB和Superset BI并导入实时数据?

sql - 如何查询最后 3 次出现的所有行的平均数据

php - Web 应用程序中的 "Undoing deletes"?

c# - 如何在 C# 中使用 TransactionScope?

postgresql - 使用 PostgreSQL MVCC 跨多个表的事务隔离

ruby-on-rails - 如何将新闻源中的项目排序为 last_active_at?

sql - PostgreSQL 递归聚合节点

sql - 外部事务失败时回滚内部事务

sql - 使用 txid 获取最新的未处理、更新的行