Mac M1 Sonoma环境下PostgreSQL角色不存在问题求助
问题描述
我在Mac M1(Sonoma系统)上通过Homebrew安装了PostgreSQL 14.10,遇到以下错误:
- 运行
psql时:PostgreSQL error: Fatal: role "username" does not exist
- 运行
psql -h localhost -U postgres时:PostgreSQL error: Fatal: role "postgres" does not exist
执行/opt/homebrew/bin/createuser -s postgres后无任何变化,以下是相关命令输出:
命令输出详情
psql --version返回:
psql (PostgreSQL) 14.10 (Homebrew)
export返回:
HOME=/Users/username HOMEBREW_CELLAR=/opt/homebrew/Cellar HOMEBREW_PREFIX=/opt/homebrew HOMEBREW_REPOSITORY=/opt/homebrew INFOPATH=/opt/homebrew/share/info: LOGNAME=username MANPATH=/opt/homebrew/share/man:: OLDPWD=/Users/username PATH=/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin PWD=/Users/username SHELL=/bin/zsh SHLVL=1 TERM=xterm-256color USER=username
ps ax | grep postgres返回:
50147 ?? S 0:00.08 /opt/homebrew/opt/postgresql@14/bin/postgres -D /opt/homebrew/var/postgresql@14 50149 ?? Ss 0:00.01 postgres: checkpointer 50150 ?? Ss 0:00.05 postgres: background writer 50151 ?? Ss 0:00.03 postgres: walwriter 50152 ?? Ss 0:00.06 postgres: autovacuum launcher 50153 ?? Ss 0:00.08 postgres: stats collector 50154 ?? Ss 0:00.00 postgres: logical replication launcher 51978 s002 S+ 0:00.00 grep postgres
psql postgres返回:
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL: role "username" does not exist
psql -d postgres -U username和psql -d postgres -U "username"返回:
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL: role "username" does not exist
请问还有其他可行的解决办法吗?
解决办法
1. 单用户模式创建缺失角色
因为当前PostgreSQL实例没有默认角色,先停止服务,用PostgreSQL系统用户启动单进程模式创建角色:
- 停止服务:
brew services stop postgresql@14 - 启动单用户模式(替换
username为你的系统用户名):sudo -u _postgres /opt/homebrew/opt/postgresql@14/bin/postgres --single -D /opt/homebrew/var/postgresql@14 postgres - 在单用户命令行中执行SQL创建角色:
输入CREATE ROLE username WITH LOGIN SUPERUSER; CREATE ROLE postgres WITH LOGIN SUPERUSER;\q退出单用户模式,再重启服务:brew services start postgresql@14
2. 重新初始化数据库(会清空现有数据)
如果单用户模式无效,直接重置数据库:
- 停止服务:
brew services stop postgresql@14 - 备份现有数据目录(可选):
mv /opt/homebrew/var/postgresql@14 /opt/homebrew/var/postgresql@14_backup - 初始化数据库,指定默认
postgres角色:initdb -D /opt/homebrew/var/postgresql@14 -U postgres - 启动服务并创建你的系统用户角色:
brew services start postgresql@14 createuser -s username
3. 修正服务运行用户权限
从进程输出看,PostgreSQL是用你的系统用户启动的,可能导致权限异常:
- 编辑服务配置文件:
open /opt/homebrew/Cellar/postgresql@14/14.10/homebrew.mxcl.postgresql@14.plist - 找到
<key>UserName</key>,确保对应的值是_postgres,修改后保存。 - 重启服务:
brew services restart postgresql@14
内容的提问来源于stack exchange,提问作者atw
相关产品推荐
相关产品推荐

