createuser
PostgreSQLでユーザー(ROLE)を作成できます。そのユーザー(名前)がすでに存在するかどうかを確認する簡単な方法はありますか?それ以外の場合、createuserはエラーで戻ります。
createuser: creation of new role failed: ERROR: role "USR_NAME" already exists
更新:スクリプト内での自動化が容易になるように、ソリューションはシェルから実行可能であることが望ましいです。
createuser
PostgreSQLでユーザー(ROLE)を作成できます。そのユーザー(名前)がすでに存在するかどうかを確認する簡単な方法はありますか?それ以外の場合、createuserはエラーで戻ります。
createuser: creation of new role failed: ERROR: role "USR_NAME" already exists
更新:スクリプト内での自動化が容易になるように、ソリューションはシェルから実行可能であることが望ましいです。
SELECT 1 FROM pg_roles WHERE rolname='USR_NAME'
そして、コマンドラインに関して(Erwinのおかげで):
psql postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='USR_NAME'"
見つかった場合は1を生成し、それ以外は生成しません。
あれは:
psql postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='USR_NAME'" | grep -q 1 || createuser ...
dbが存在するかどうかを確認するのと同じ考えに従う
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
これがPythonでこれを行っている可能性のある人に役立つことを願っています。
GitHubGistで完全に機能するスクリプト/ソリューションを作成しました。このコードスニペットの下のURLを参照してください。
# ref: https://stackoverflow.com/questions/8546759/how-to-check-if-a-postgres-user-exists
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://stackoverflow.com/questions/37488175/simplify-database-psycopg2-usage-by-creating-a-module
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))
べき等リモート(RDS)PostgreSQLを提供し、CMモジュールなどを使用せずにPythonからロール/ユーザーを作成します。
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"