我正在寻找一种方法来列出OpenSuse postgresql服务器上的所有数据库和所有模式。我知道我可以使用\l+
等元命令列出所有数据库,但有没有办法列出所有数据库的所有信息,包括数据库,架构和大小信息?
我想要一种整体看待一切的方法。
谢谢!
答案 0 :(得分:2)
从PostgreSQL 9.4.1开始,以下查询将在\l+
中提供与psql
相同的输出:
SELECT
d.datname as "Name",
pg_catalog.pg_get_userbyid(d.datdba) as "Owner",
pg_catalog.pg_encoding_to_char(d.encoding) as "Encoding",
d.datcollate as "Collate",
d.datctype as "Ctype",
pg_catalog.array_to_string(d.datacl, E'\n') as "Access privileges",
CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')
THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(d.datname))
ELSE 'No Access'
END as "Size",
t.spcname as "Tablespace",
pg_catalog.shobj_description(d.oid, 'pg_database') as "Description"
FROM
pg_catalog.pg_database d
JOIN
pg_catalog.pg_tablespace t on d.dattablespace = t.oid
ORDER BY 1;
以下是来源:src/bin/psql/describe.c
答案 1 :(得分:1)
我没有看到获取数据库模式列表而无需先连接它的方法。基于this,我认为您可以使用db_link来获取它,例如:
CREATE OR replace FUNCTION databases_schemas_size
() returns setof RECORD
AS
$body$
DECLARE
connection_info CHARACTER varying;
i RECORD;
r RECORD;
BEGIN
FOR r IN SELECT cast(datname AS CHARACTER varying) FROM pg_database WHERE datistemplate = FALSE LOOP
SELECT format ('dbname=%s user=%s password=%s', r.datname, 'YOUR_ALLOWED_USERNAME', 'PASSWORD') INTO connection_info;
perform dblink_connect(connection_info);
FOR i IN SELECT r.datname, *
FROM dblink('SELECT nspname , pg_size_pretty(sum(pg_relation_size(C.oid))) AS size FROM pg_class C LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace) WHERE nspname NOT IN (''pg_catalog'', ''information_schema'') group by nspname')
AS t(schema_name CHARACTER varying, schema_size text)
LOOP
RETURN NEXT i;
END LOOP;
perform dblink_disconnect();
END LOOP;
RETURN;
END;
$body$ LANGUAGE plpgsql volatile cost 100;
SELECT * FROM databases_schemas_size()
AS (datname CHARACTER varying, schema_name CHARACTER varying, schema_size text);
对其进行改进,以便不对登录名/密码进行硬编码