Create PostgreSQL ROLE (user) if it doesn't exist

前端 未结 10 1778
旧时难觅i
旧时难觅i 2020-12-12 15:47

How do I write an SQL script to create a ROLE in PostgreSQL 9.1, but without raising an error if it already exists?

The current script simply has:

CR         


        
10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 16:28

    Bash alternative (for Bash scripting):

    psql -h localhost -U postgres -tc \
    "SELECT 1 FROM pg_user WHERE usename = 'my_user'" \
    | grep -q 1 \
    || psql -h localhost -U postgres \
    -c "CREATE ROLE my_user LOGIN PASSWORD 'my_password';"
    

    (isn't the answer for the question! it is only for those who may be useful)

提交回复
热议问题