我有一个正在进行的项目,就是要对Postgres数据库中的所有对象进行注释,从而记录所有的对象和它们的功能。有没有一个 SELECT
脚本,可以显示所有的表、视图、列、函数等,以及它们的注释,包括有空注释的表。下面是一个我想要的例子。
SELECT object_type,object_schema,object_name,comment
FROM information_schema.some_table_out_there;
|object_type|object_schema|object_name|comment|
|table | my_schema |table1 |my first table
|table | my_schema |table2 |NULL
|view | public |employees |NULL
|function | public |emps_insert|inserts employees
我想用这个脚本来创建一个报告 在这个报告中,你可以钻到一个表格中,然后在数据库对象上写上你想要的注释。
information_schema
是由一个 ANSI标准所以它只涵盖了SQL规范所描述的对象。索引不包括在内,也不包括任何Postgres特有的东西(事件触发器、行安全策略等)。如果你想得到一个详尽的列表,你需要去查看 系统目录.
没有对象的中心列表;每个对象类型都住在自己的表中,所以你需要分别查询每个对象。然而,有一些方便的 对象信息功能 它将接受任何对象类型,所以我们可以通过一些动态SQL将这些查询相当容易地粘合在一起。
create function describe_all_objects()
returns table(
type text,
schema text,
name text,
identity text,
comment text
)
as $$
declare
/* Cutoff for system object OIDs; see comments in src/include/access/transam.h */
MIN_USER_OID constant oid = 16384;
catalog_class regclass;
begin
for catalog_class in
/* Get a list of all catalog tables with an OID */
select oid::regclass
from pg_class
where
relhasoids and
pg_class.oid < MIN_USER_OID and
/* Enum members have no obj_description(); the enum itself is picked up in pg_type */
pg_class.oid <> 'pg_enum'::regclass
loop
return query execute format(
$SQL$
/* Get descriptions for all user-created catalog entries */
select
info.type,
info.schema,
info.name,
info.identity,
coalesce(
obj_description(catalog_table.oid, catalog_table.tableoid::regclass::text),
shobj_description(catalog_table.oid, catalog_table.tableoid::regclass::text)
) as comment
from
%s as catalog_table,
lateral pg_identify_object(catalog_table.tableoid, catalog_table.oid, 0) as info
where
catalog_table.oid >= %s
$SQL$,
catalog_class,
MIN_USER_OID
);
end loop;
/* Handle "sub-objects" (i.e. pg_attribute) separately */
return query
select
info.type,
info.schema,
info.name,
info.identity,
col_description(attrelid, attnum) as comment
from
pg_attribute,
lateral pg_identify_object('pg_class'::regclass, attrelid, attnum) as info
where
attrelid >= MIN_USER_OID and
attnum >= 0 and
not attisdropped;
end
$$
language plpgsql stable;
select * from describe_all_objects();
这应该包括 每一 对象,直到隐含的表数组类型和TOAST表索引上的列,以及服务器范围内的对象,如数据库和用户,所以你可能会想要过滤掉很多东西。
少数目录表需要超级用户权限才能直接访问,但如果这是一个问题,你应该能够修改查询,从一些公共源中提取信息(例如 pg_authid
是超级用户专用的,因为它包含密码信息,但你可以查看 pg_roles
代替)。)
如果你注意到有任何遗漏,请告诉我(并且请在使用它做任何重要的事情之前,比我更彻底地测试它:)。).