如何检查postgres用户是否存在?
createuser
允许在 PostgreSQL 中创建用户 (ROLE)。有没有一种简单的方法来检查该用户(名称)是否已经存在?否则 createuser 返回并显示错误:
createuser: creation of new role failed: ERROR: role "USR_NAME" already exists
更新:该解决方案最好可以从 shell 执行,以便更容易在脚本内实现自动化。
createuser
allows creation of a user (ROLE) in PostgreSQL. Is there a simple way to check if that user(name) exists already? Otherwise createuser returns with an error:
createuser: creation of new role failed: ERROR: role "USR_NAME" already exists
UPDATE: The solution should be executable from shell preferrably, so that it's easier to automate inside a script.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
就命令行而言(感谢 Erwin):
如果找到则返回 1,除此之外别无其他。
那是:
And in terms of command line (thanks to Erwin):
Yields 1 if found and nothing else.
That is:
遵循相同的想法检查数据库是否存在
并且你可以在这样的脚本中使用它:
Following the same idea than to check if a db exists
and you can use it in a script like this:
要完全在单个 psql 命令中完成此操作:
To do this entirely within a single psql command:
psql -qtA -c "\du USR_NAME" | psql -qtA -c "\du USR_NAME" |剪切-d“|” -f 1
[[ -n $(psql -qtA -c "\du ${1}" | cut -d "|" -f 1) ]] &&回显“存在”|| echo“不存在”
psql -qtA -c "\du USR_NAME" | cut -d "|" -f 1
[[ -n $(psql -qtA -c "\du ${1}" | cut -d "|" -f 1) ]] && echo "exists" || echo "does not exist"
希望这对那些可能在 python 中执行此操作的人有所帮助。
我在 GitHubGist 上创建了一个完整的工作脚本/解决方案 - 请参阅此代码片段下面的 URL。
提供幂等远程(RDS)PostgreSQL从python创建角色/用户,无需CM模块等
Hope this helps those of you who might be doing this in python.
I created a complete working script/solution on a GitHubGist--see URL below this code snippet.
Provides idempotent remote (RDS) PostgreSQL create role/user from python without CM modules, etc.
受到接受的答案的启发,不幸的是这对我不起作用(直接
psql
调用时出错) ,然后我做了这样的事情:即使我认为 grep -E "1 rows" 在这里是安全的,因为我们不应该有超过一个同名的用户,我更喜欢保留 grep -乙“[1-9][0-9]* rows” 以获得返回成功的通用“我得到 1 个或多个结果”。
如果失败,我会输入
exit 1
,因为我所在的脚本需要创建此用户才能正常运行。Inspired from accepted answer, that unfortunately did not work for me (error on direct
psql
call), I then did something like this:Even if I think
grep -E "1 rows"
is safe here since we should not have more that one user of same name, I prefer keepinggrep -E "[1-9][0-9]* rows"
to get a generic "I got 1 or more result(s)" returning success.And I put
exit 1
if it fails because I'm on a script that needs this user created to run properly.PHP 的完整片段:
此外,最好在列名“rolname”前面提及系统目录/表名“pg_roles”。像这样:“pg_roles.rolname”。
并提及它,因为它让我困惑:它实际上拼写为“rolname”而不是“rolename”。
A complete snippet for PHP:
and furthermore, it might be better to mention the system catalog/table name "pg_roles" in front of the column name "rolname". Like this: "pg_roles.rolname".
and to mention it, because it confused me: it is really spelled "rolname" and not "rolename".