2012-06-08 42 views
23

有誰知道如何在Postgres 9.1中找到表的OID?我正在編寫一個更新腳本,它在嘗試創建列之前需要測試表中列是否存在。這是爲了防止第一個錯誤後運行腳本。確定Postgres 9.1中的表的OID?

回答

18

postgres目錄表pg_class是你應該看看。每個表應該有一行,表名在relname列中,並且隱藏列中的oid爲oid

該目錄表位於postgres數據庫中,因此請確保連接到該數據庫,而不是您的應用程序數據庫。

您可能也有興趣pg_attribute目錄表,其中包括每表列一行。

見:http://www.postgresql.org/docs/current/static/catalog-pg-class.htmlhttp://www.postgresql.org/docs/current/static/catalog-pg-attribute.html

+1

我曾經看過'pg_class'和'pg_attribute'表中的文檔,但我不知道'pg_class'表中有一個名爲'oid'的隱藏列。我無法弄清楚文檔的來源。謝謝! –

+6

這不太準確。每個數據庫都有一個名爲'pg_catalog'的模式,其中包含特定於數據庫的目錄表。 –

+0

我第二@TonyVitabile。這是我正在尋找的隱藏專欄「oid」。 –

31

有一個簡單的方法來獲得一個表OID。投射到object-identifier classregclass(同時連接到各個DB):

SELECT 'mytbl'::regclass::oid; 

缺省爲所述第一模式在search_path或如果沒有找到引發一個例外。
或者明確地架構資格:

SELECT 'myschema.mytbl'::regclass::oid; 

然後你只需要檢查目錄表pg_attribute該列的存在:

SELECT TRUE AS col_exists 
FROM pg_attribute 
WHERE attrelid = 'mytbl'::regclass 
AND attname = 'mycol' 
AND NOT attisdropped -- no dropped (dead) columns 
-- AND attnum > 0  -- no system columns (you may or may not want this) 

在Postgres裏9.4或更高版本,你也可以使用to_regclass('mytbl') ,如果未找到表格,則不會引發異常:

0
SELECT oid FROM pg_class WHERE relname = 'tbl_name' AND relkind = 'r'; 
+1

說明會很好... – eirikir

相關問題