本文介绍了如何检查postgres用户是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
createuser
允许在PostgreSQL中创建用户(ROLE)。有没有一种简单的方法来检查该用户(名称)是否已经存在?否则,createuser会返回错误:
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
更新:该解决方案最好是可以从Shell执行,这样可以更轻松地在脚本内部自动化。
UPDATE: The solution should be executable from shell preferrably, so that it's easier to automate inside a script.
推荐答案
SELECT 1 FROM pg_roles WHERE rolname='USR_NAME'
在命令行方面(感谢Erwin):
And in terms of command line (thanks to Erwin):
psql postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='USR_NAME'"
如果发现1,则获得1。
Yields 1 if found and nothing else.
即:
psql postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='USR_NAME'" | grep -q 1 || createuser ...
这篇关于如何检查postgres用户是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!