gpt4 book ai didi

postgresql - 仅使用 SELECT 从 information_schema 中查找 Postgresql 中表的主键

转载 作者:行者123 更新时间:2023-11-29 12:13:28 24 4
gpt4 key购买 nike

我正在使用以下查询来发现 (1) 主键列和 (2) 这些列是否具有来自 Postgresql 9.1 中的 information_schema 的默认值。

SELECT kcu.column_name, (c.column_default is not null) AS has_default 
FROM information_schema.key_column_usage kcu
JOIN information_schema.table_constraints tc ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.columns c on c.column_name = kcu.column_name and c.table_name = kcu.table_name
WHERE tc.constraint_type = 'PRIMARY KEY' AND kcu.table_name like :tablename

当以数据库所有者身份运行时它工作正常,但当我以“只读”用户身份运行它时(我需要在我的应用程序中这样做),它不返回任何数据。一些研究表明问题出在 information.table_constraints View 上;来自文档:

The view table_constraints contains all constraints belonging to tables that the current user owns or has some non-SELECT privilege on.

那么为了检索 table_constraints,我的登录角色需要的不仅仅是表上的 SELECT?如果不授予登录角色写入权限,是否无法从 information_schema 获取信息?

最佳答案

使用 pg_* View 而不是 information_schema View 。
pg_* View 显示所有信息,而不管授予的权限。

试试这个查询:

select
t.relname as table_name,
i.relname as index_name,
a.attname as column_name,
d.adsrc as default_value
from
pg_class t
join pg_attribute a on a.attrelid = t.oid
join pg_index ix on t.oid = ix.indrelid AND a.attnum = ANY(ix.indkey)
join pg_class i on i.oid = ix.indexrelid
left join pg_attrdef d on d.adrelid = t.oid and d.adnum = a.attnum
where
t.relkind = 'r'
and t.relname in ( 'aa', 'bb', 'cc' )
order by
t.relname,
i.relname,
a.attnum;

查询结果示例:

create table aa(
x int primary KEY
);

create table bb(
x int default 1,
constraint pk primary key ( x )
);

create table cc(
x int default 20,
y varchar(10) default 'something',
constraint cc_pk primary key ( x, y )
);

table_name | index_name | column_name | default_value
------------+------------+-------------+--------------------------------
aa | aa_pkey | x |
bb | pk | x | 1
cc | cc_pk | x | 20
cc | cc_pk | y | 'something'::character varying

关于postgresql - 仅使用 SELECT 从 information_schema 中查找 Postgresql 中表的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18516931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com