createuser
可以在 PostgreSQL 中创建一个用户(角色)。有没有一种简单的方法来检查该用户(名称)已经存在?否则, createuser
将返回错误:
createuser: creation of new role failed: ERROR: role "USR_NAME" already exists
更新:最好可以从shell中执行解决方案,这样更容易在脚本中自动化。
createuser
可以在 PostgreSQL 中创建一个用户(角色)。有没有一种简单的方法来检查该用户(名称)已经存在?否则, createuser
将返回错误:
createuser: creation of new role failed: ERROR: role "USR_NAME" already exists
更新:最好可以从shell中执行解决方案,这样更容易在脚本中自动化。
SELECT 1 FROM pg_roles WHERE rolname='USR_NAME'
在命令行方面(感谢Erwin):
psql postgres -tXAc "SELECT 1 FROM pg_roles WHERE rolname='USR_NAME'"
如果找到了,就返回1,否则什么也不返回。
也就是说:
psql postgres -tXAc "SELECT 1 FROM pg_roles WHERE rolname='USR_NAME'" | grep -q 1 || createuser ...
按照与检查数据库是否存在相同的思路
psql -t -c '\du' | cut -d \| -f 1 | grep -qw <user_to_check>
您可以像这样在脚本中使用它:
if psql -t -c '\du' | cut -d \| -f 1 | grep -qw <user_to_check>; then
# user exists
# $? is 0
else
# ruh-roh
# $? is 1
fi
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。
# ref: https://dev59.com/yWoy5IYBdhLWcg3wcNrh
check_user_cmd = ("SELECT 1 FROM pg_roles WHERE rolname='%s'" % (deis_app_user))
# our create role/user command and vars
create_user_cmd = ("CREATE ROLE %s WITH LOGIN CREATEDB PASSWORD '%s'" % (deis_app_user, deis_app_passwd))
# ref: https://dev59.com/T5ffa4cB1Zd3GeqP8nxA
class RdsCreds():
def __init__(self):
self.conn = psycopg2.connect("dbname=%s user=%s host=%s password=%s" % (admin_db_name, admin_db_user, db_host, admin_db_pass))
self.conn.set_isolation_level(0)
self.cur = self.conn.cursor()
def query(self, query):
self.cur.execute(query)
return self.cur.rowcount > 0
def close(self):
self.cur.close()
self.conn.close()
db = RdsCreds()
user_exists = db.query(check_user_cmd)
# PostgreSQL currently has no 'create role if not exists'
# So, we only want to create the role/user if not exists
if (user_exists) is True:
print("%s user_exists: %s" % (deis_app_user, user_exists))
print("Idempotent: No credential modifications required. Exiting...")
db.close()
else:
print("%s user_exists: %s" % (deis_app_user, user_exists))
print("Creating %s user now" % (deis_app_user))
db.query(create_user_cmd)
user_exists = db.query(check_user_cmd)
db.close()
print("%s user_exists: %s" % (deis_app_user, user_exists))
要在单个psql命令中完成此操作:
DO $$BEGIN
IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'USR_NAME')
THEN CREATE ROLE USR_NAME;
END IF;
END$$;
psql
调用时出现错误),然后我做了类似于这样的操作:if ! echo "SELECT * FROM pg_roles WHERE rolname='USR_NAME'" | psql -h localhost -U postgres | grep -E "[1-9][0-9]* rows"; then
# User not found, create it
if ! echo "CREATE USER USR_NAME WITH PASSWORD 'USR_NAME' CREATEDB SUPERUSER" | psql -h localhost -U postgres; then
echo "Error creating USR_NAME"
exit 1
fi
fi
grep -E "1 rows"
是安全的,因为我们不应该有相同名称的多个用户,但我更喜欢保留 grep -E "[1-9][0-9]* rows"
,以获得一个通用的“我得到了1个或多个结果”的成功返回。
如果失败,我会放置 exit 1
,因为我在一个需要这个用户创建才能正常运行的脚本中。
psql
是一个命令。但是如果你在谈论createuser
命令行实用程序(显然是这样,我一开始没有注意到create user
中缺少空格),那么忽略退出状态并将输出重定向到/dev/null
可能更容易些。 - Michael Krelin - hackerpsql postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='USR_NAME'"
。如果找到,则返回1
,否则没有其他输出。 - Erwin Brandstetterecho "SELECT rolname FROM pg_roles WHERE rolname='USR_NAME';" | psql | grep -c USR_NAME
。请将您的解决方案作为答案添加,不要在psql后面加上“postgres”。 - m33lky-X
标志以防止读取.psqlrc
文件。这个文件通常会打开\timing
,这很容易与grep -q 1
产生误报,因为时间值通常包含1
。所以,psql postgres -tXAc ...
。 - jbranchaud