Prevent connection of new users." PGPASSWORD=$PG_PASSWORD-6ren">
gpt4 book ai didi

postgresql - 为什么 Postgres dropdb 工作但 psql DROP DATABASE 不工作?

转载 作者:行者123 更新时间:2023-11-29 14:26:46 25 4
gpt4 key购买 nike

我正在编写一个将删除 PostgreSQL 数据库的脚本。我这样做:

echo "> Prevent connection of new users."
PGPASSWORD=$PG_PASSWORD_IMPORT psql \
-h $PG_HOST_IMPORT -p $PG_PORT_IMPORT -U $PG_USER_IMPORT -d $PG_DATABASE_IMPORT \
-c "REVOKE CONNECT ON DATABASE $PG_DATABASE_IMPORT FROM PUBLIC, $PG_USER_IMPORT;"

echo "> Terminate existing connections."
PGPASSWORD=$PG_PASSWORD_IMPORT psql \
-h $PG_HOST_IMPORT -p $PG_PORT_IMPORT -U $PG_USER_IMPORT -d $PG_DATABASE_IMPORT \
-c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid() AND datname = '$PG_DATABASE_IMPORT';"

echo "> Drop '$PG_DATABASE_IMPORT' database."
PGPASSWORD=$PG_PASSWORD_IMPORT dropdb \
-h $PG_HOST_IMPORT -p $PG_PORT_IMPORT -U $PG_USER_IMPORT $PG_DATABASE_IMPORT

而且效果很好。

但是当我尝试使用 psql 删除数据库时,出现错误错误:无法删除当前打开的数据库。

echo "> Prevent connection of new users."
PGPASSWORD=$PG_PASSWORD_IMPORT psql \
-h $PG_HOST_IMPORT -p $PG_PORT_IMPORT -U $PG_USER_IMPORT -d $PG_DATABASE_IMPORT \
-c "REVOKE CONNECT ON DATABASE $PG_DATABASE_IMPORT FROM PUBLIC, $PG_USER_IMPORT;"

echo "> Terminate existing connections."
PGPASSWORD=$PG_PASSWORD_IMPORT psql \
-h $PG_HOST_IMPORT -p $PG_PORT_IMPORT -U $PG_USER_IMPORT -d $PG_DATABASE_IMPORT \
-c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid() AND datname = '$PG_DATABASE_IMPORT';"

echo "> Drop '$PG_DATABASE_IMPORT' database."
PGPASSWORD=$PG_PASSWORD_IMPORT psql \
-h $PG_HOST_IMPORT -p $PG_PORT_IMPORT -U $PG_USER_IMPORT -d $PG_DATABASE_IMPORT \
-c "DROP DATABASE $PG_DATABASE_IMPORT;"

我觉得很奇怪,因为根据文档,dropdb 是 SQL 命令 DROP DATABASE 的包装器。

最佳答案

The dropdb documentation说:

--maintenance-db=<strong><em>dbname</em></strong>

    Specifies the name of the database to connect to in order to drop the target database. If not specified, the postgres database will be used; if that does not exist (or is the database being dropped), template1 will be used.

dropdb连接到 postgres ,而不是要删除的数据库,这就是它在这种情况下起作用的原因。

关于postgresql - 为什么 Postgres dropdb 工作但 psql DROP DATABASE 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57018140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com