无法通过用户名直接连接psql?PostgreSQL默认库匹配异常
问题:psql未指定数据库时无法通过非postgres用户连接PostgreSQL
当执行psql -h localhost -p 5432 -U myuser命令尝试连接时,PostgreSQL会将用户名(myuser)解析为默认数据库名,因此除非同时指定数据库,否则无法继续操作;但使用用户名postgres可以正常访问,原因是存在同名的postgres数据库。
以下是终端操作示例:
MacBook % psql -h localhost -p 5432 -U myuser psql: error: connection to server at "localhost" (::1), port 5432 failed: FATAL: database "myuser" does not exist MacBook % psql -h localhost -p 5432 -U private psql: error: connection to server at "localhost" (::1), port 5432 failed: FATAL: database "private" does not exist MacBook % psql -h localhost -p 5432 -U postgres psql (14.11 (Homebrew)) Type "help" for help. postgres=# \du List of roles Role name | Attributes | Member of -----------+------------------------------------------------------------+----------- myuser | | {} postgres | Superuser | {} private | Superuser, Create role, Create DB, Replication, Bypass RLS | {} postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges ------------+---------+----------+---------+-------+--------------------- mydatabase | private | UTF8 | C | C | =Tc/private + | | | | | private=CTc/private+ | | | | | myuser=CTc/private postgres | private | UTF8 | C | C | template0 | private | UTF8 | C | C | =c/private + | | | | | private=CTc/private template1 | private | UTF8 | C | C | =c/private + | | | | | private=CTc/private (4 rows) postgres=# \q MacBook % psql -h localhost -p 5432 -U myuser -d mydatabase psql (14.11 (Homebrew)) Type "help" for help. mydatabase-> \du List of roles Role name | Attributes | Member of -----------+------------------------------------------------------------+----------- myuser | | {} postgres | Superuser | {} private | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
版本信息:
PostgreSQL 14.11 (Homebrew) on x86_64-apple-darwin23.2.0,由Apple clang version 15.0.0 (clang-1500.1.0.2.5)编译,64位
已尝试的解决方案及结果:
- 使用
private用户连接,结果与myuser相同,因不存在名为private的数据库报错 - 执行
postgres=# ALTER ROLE myuser SET search_path TO mydatabase, pg_catalog;修改search_path,无效果 - 重建
share/postgresql@14/目录下的pg_hba.conf和postgresql.conf文件(原目录只有示例文件),问题未解决
需求:希望能够通过psql -h localhost -p 5432 -U myuser直接访问数据库,无需添加-d mydatabase参数。
内容的提问来源于stack exchange,提问作者Leo
相关产品推荐
相关产品推荐

