programing

postgres 사용자가 존재하는지 확인하는 방법은 무엇입니까?

bestprogram 2023. 5. 22. 21:50

postgres 사용자가 존재하는지 확인하는 방법은 무엇입니까?

createuserPostgre에서 사용자(ROLE)를 생성할 수 있습니다.SQL. 해당 사용자(이름)가 이미 존재하는지 확인할 수 있는 간단한 방법이 있습니까?그렇지 않으면 다음 오류와 함께 사용자 반환을 만듭니다.

createuser: creation of new role failed: ERROR:  role "USR_NAME" already exists

업데이트: 스크립트 내에서 자동화하기 쉽도록 솔루션을 셸에서 실행하는 것이 좋습니다.

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 ...

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

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"

이것이 파이썬에서 이것을 하고 있을 수 있는 사람들에게 도움이 되기를 바랍니다.
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(동등한 원격) Postgre 제공SQL은 CM 모듈이 없는 python 등에서 역할/사용자를 생성합니다.

단일 psql 명령 내에서 전체적으로 이 작업을 수행하려면 다음을 수행합니다.

DO $$BEGIN
IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'USR_NAME')
THEN CREATE ROLE USR_NAME;
END IF;
END$$;

언급URL : https://stackoverflow.com/questions/8546759/how-to-check-if-a-postgres-user-exists