Why does the postgres tx id not start at 1 for a newly created database?

余生长醉 提交于 2021-01-28 07:15:21

问题


I am trying to understand the details of how postgres deals with transactions; I noticed that when the execute the following commands on psql I get a txid that is at 518526 instead of a low number like 0 or 1 which is what I expected would happen.

postgres=# CREATE DATABASE test;
CREATE DATABASE
postgres=# \connect test;
You are now connected to database "test" as user "postgres".
test=# begin;
BEGIN
test=# select txid_current();
 txid_current 
--------------
       518526
(1 row)

On a second psql console I type

postgres=# CREATE DATABASE test3;
CREATE DATABASE
postgres=# \connect test3
You are now connected to database "test3" as user "postgres".
test3=# begin;
BEGIN
test3=# select txid_current();
 txid_current 
--------------
       518528
(1 row)

So it looks like for all databases in the postgres server the next txid seems to be shared across all databases. Why does postgres use txid across databases not on a per database basis?


回答1:


The transaction ID counter is global across the server. This is necessary partly because PostgreSQL has some global tables, like pg_database, pg_role, etc that are visible across all databases. To make these transactional we need a global transaction ID.

You shouldn't be using the transaction ID for anything except an identifier for a transaction. You can't even assume that a lower transaction ID is an older transaction, due to transaction ID wrap-around.

You can use txid_current_snapshot and txid_visible_in_snapshot (if you're on a new enough PostgreSQL) to reason about visibility. Surprisingly, I don't see a system function to compare two transaction IDs with respect to the current global xmin for transaction wrap-around.



来源:https://stackoverflow.com/questions/20600684/why-does-the-postgres-tx-id-not-start-at-1-for-a-newly-created-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!