"postgres" 数据库在 PostgreSQL 中是否始终可用?

Is the "postgres" database always available in PostgreSQL?

我正在编写一个脚本,需要获取 postgres 集群中的所有数据库,因此它需要连接到一个数据库(无论哪个数据库)来执行此操作。

是否可以假设 "postgres" 数据库将始终可以连接到,或者如果不能,是否有一种编程方式来确定集群中我可以连接到的任意数据库?

根据我的个人经验,是的,几乎可以保证它会存在。但是,根据 PostgreSQL 官方文档:

The database server itself does not require the postgres database to exist, 
but many external utility programs assume it exists.

因此,您不能假设它总是可用,尽管在实践中,它几乎肯定可用。

PostgreSQL 有三个 "system" 数据库:postgres、template0 和 template1。我很确定所有这些都可以删除。 (您可能想在虚拟机中对此进行测试。)我确定 特权用户可以删除 postgres 和 template1。默认情况下,template0 不接受连接。

话虽如此,"postgres"的主要目的是给大家a database to connect to

The postgres database is also created when a database cluster is initialized. This database is meant as a default database for users and applications to connect to. It is simply a copy of template1 and can be dropped and recreated if necessary.

所以这是一个合理的假设,但不是万无一失的假设。我可以想象一些偏执(谨慎)的商店可能会放弃 "postgres" 并使用不同的数据库作为他们的内部默认数据库,以防他们的服务器受到威胁。这有点像为 SSH 使用非默认端口。