首页 > 解决方案 > Postgres 临时表是否存在于同时打开的多个连接之间?

问题描述

假设我打开一个新的npgsqlconnection并创建一个新的临时表temp1,然后打开另一个新连接。据我了解,临时表仅对打开它的会话可用,并且两个打开的连接不应共享同一个会话。这里的连接字符串是相同的,我尝试关闭池,但这并没有改变任何东西。伪代码是:

var conn1 = new NpgsqlConnection(MyConnectionString)
var conn2 = new NpgsqlConnection(MyConnectionString)
conn1.Open()
conn2.Open()
conn1.Execute("CREATE TEMP TABLE temp1(idx int)")

如果我对两个连接都执行查询SELECT COUNT(*) FROM pg_tables WHERE tablename = 'temp1',则此查询返回 1。为什么conn2能够访问在 上创建的临时表conn1?有没有办法防止这种情况发生?

标签: postgresqlnpgsql

解决方案


为什么 conn2 能够访问在 conn1 上创建的临时表?

它不能。

其他连接可以通过系统目录看到有一个表,但他们无法访问它。

-- Connection 1
test=# SELECT schemaname FROM pg_tables WHERE tablename = 'temp1';
 schemaname 
------------
 pg_temp_3
(1 row)

-- Connection 2
test=# select * from pg_temp_3.temp1;
ERROR:  cannot access temporary tables of other sessions

推荐阅读