如何使用带有 createdb 和 URI 的终端?

How to use terminal with createdb and URI?

URI connection-string可以这么复杂,这里有一个标准的例子:

  createdb "postgresql://postgres:postgres@localhost:5432/sandbox"

当然,它不适用于 createdb ("template1: FATAL"),这就是问题所在。 URI 在 psql 下工作正常,例如。

  psql "postgresql://postgres:postgres@localhost:5432/postgres"

我正在寻找具有预期行为的任何东西,无论命令名称是否不是 createdb.


PS1:在我的环境中。即使是 postgres 用户也有密码等,我所有的脚本都使用 URI 连接字符串 标准,没有更多 -U 等选项。这个问题的重点是URI标准。使用现代客户端和连接,v9+.

PS2:作为它的传统和哲学,我们期望PostgreSQL提供的命令中有orthogonal behaviourpsqlpg_dump 关于 URI 是正交的; psqlpg_dumpcreatedb 关于 -U 选项是正交的...我预计 URI 使用会有些正交...
或者有一个 架构错误?

https://www.postgresql.org/docs/current/static/app-createdb.html createdb 不声称接受 URI 作为 dbname,而 psql 则: https://www.postgresql.org/docs/current/static/app-psql.html

当你

时会发生什么
 createdb "postgresql://postgres:postgres@localhost:5432/sandbox"

它应该按原样读取第一个参数并使用这样的名称创建数据库(顺便说一句,这发生在我身上):

MacBook-Air:~ vao$ psql t -c "\l pos*"
Timing is on.
Pager usage is off.
                                               List of databases
                         Name                          | Owner | Encoding | Collate | Ctype | Access privileges
-------------------------------------------------------+-------+----------+---------+-------+-------------------
 postgres                                              | vao   | UTF8     | C       | UTF-8 |
 postgresql://postgres:postgres@localhost:5432/sandbox | vao   | UTF8     | C       | UTF-8 |

此行为符合手册:

dbname

Specifies the name of the database to be created.

要创建的数据库的名称,而 psql 数据库名可以是要连接到的数据库的 uri...

您可以尝试设置 PGHOSTPGHOSTADDRPGPORTPGDATABASEPGUSERPGPASSWORD 环境变量,如 Environment Variables 文档部分。

希望对您有所帮助。

clusterdb、createdb、createuser、dropdb、dropuser、reindexdb 和 vacuumdb 是实用程序命令,它们是 SQL 命令的包装器。虽然没有正式弃用,但它们在任何人关心的程序列表中并不靠前。如今,大多数人都使用某种脚本来完成他们所做的事情。如果您想使用客户端程序和 URI 来执行 CREATE DATABASE 那么:

psql "postgresql://postgres:postgres@localhost:5432/postgres" -c 'CREATE DATABASE my_test_db'
Null display is "NULL".
CREATE DATABASE

或使用以下方式传入文件:

psql "postgresql://postgres:postgres@localhost:5432/postgres" -f db_create.sql

2020 年 5 月 12 日更新

似乎有一个未记录的功能现已公开。对于大多数这些命令(不是 *user),有一个 --maintenance-db 选项。来自 CREATEDB 开发文档:

--maintenance-db=dbname

Specifies the name of the database to connect to when creating the new database. If not specified, the postgres database will be used; if that does not exist (or if it is the name of the new database being created), template1 will be used. This can be a connection string. If so, connection string parameters will override any conflicting command line options.

其中连接字符串可以是URI.