如何在postgresql中列出所有数据库及其模式?

How to list all databases and their schemas in postgresql?

我正在寻找一种方法来列出OpenSuse postgresql服务器上的所有数据库和所有模式。 我知道我可以使用诸如\l+之类的元命令来列出所有数据库,但是有没有办法列出所有数据库的所有信息,包括数据库,模式和大小信息?

我想要一种整体看待一切的方法。

谢谢!


从PostgreSQL 9.4.1开始,以下查询将提供与psql中的\l+相同的输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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'
'
) 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


我没有找到一种方法来获取数据库的模式列表而不首先连接它。 基于此,我认为您可以使用db_link获取它,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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);

您可以使用FOREIGN DATA WRAPPER功能对其进行改进,以便不对登录/密码进行硬编码