[英]How to check if PostgreSQL public schema exists?
運行以下查詢:
SELECT exists (
SELECT
schema_name
FROM
information_schema.schemata
WHERE
schema_name = 'public'
) AS schema_exists;
我總是得到FALSE
,即使存在公共模式。
我應該如何檢查此架構是否存在?
編輯
我使用的是 PostgreSQL 8.4 版
我猜你看不到公共模式,因為你用來測試模式存在的數據庫角色。 information_schema.schemata
實際上是一個具有以下定義的視圖:
SELECT
current_database()::information_schema.sql_identifier AS catalog_name,
n.nspname::information_schema.sql_identifier AS schema_name,
u.rolname::information_schema.sql_identifier AS schema_owner,
NULL::character varying::information_schema.sql_identifier AS default_character_set_catalog,
NULL::character varying::information_schema.sql_identifier AS default_character_set_schema,
NULL::character varying::information_schema.sql_identifier AS default_character_set_name,
NULL::character varying::information_schema.character_data AS sql_path
FROM pg_namespace n, pg_authid u
WHERE n.nspowner = u.oid AND pg_has_role(n.nspowner, 'USAGE'::text);
這也在文檔中進行了描述。
你可以得到的視圖定義information_schema
使用\\d+
在psql里- \\d+ information_schema.schemata
在這種情況下。
您應該使用pg_namespace
而不是information_schema.schemata
來自information_schema.schemata
取決於您所連接的角色,因此通常通過查詢來發現模式並不是真正正確的視圖。
9.3 中關於information_schema.schemata
的文檔說:
視圖模式包含當前數據庫中由當前啟用的角色擁有的所有模式。
然而,僅僅從那句話中並不清楚(至少對我而言),為什么你看不到public
。
在郵件列表帖子中,Tom Lane 有一個更進一步的解釋:
見http://www.postgresql.org/message-id/11650.1357782995@sss.pgh.pa.us
他的結論:
就目前情況而言,非超級用戶不會在此視圖中看到“public”、“pg_catalog”,甚至“information_schema”本身,這似乎有點愚蠢。
這看起來與這個問題中的問題完全一樣。
底線:使用pg_namespace
而不是information_schema.schemata
這在 9.4 版中進行了修改,以符合用戶的期望。 當前文檔說:
視圖模式包含當前用戶有權訪問的當前數據庫中的所有模式(通過成為所有者或具有某些特權)。
模式上的USAGE
特權現在足以從這個視圖中獲取它。
(作為評論的答案發布)
直接引用 pg_namespace 表可能是一個不錯的解決方法......
SELECT exists(select 1 from pg_namespace where nspname = 'public') as schema_exists;
我不知道確切的區別是什么,但知道命名空間在 PostgreSQL 內部“支持”模式。
另外,我相信這些系統 pg_* 表不能保證在不同版本之間保持一致,但它至少從 7.3 開始就存在( http://www.postgresql.org/docs/7.4/static/catalog-pg-namespace. html )並且現在在那里(9.3.1)。
你寫的那個查詢應該有效......試試這個替代方案:
select count(*) > 0 FROM information_schema.schemata WHERE schema_name = 'public';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.