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

前端 未结 10 1770
旧时难觅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:35

    The same solution as for Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL? should work - send a CREATE USER … to \gexec.

    Workaround from within psql

    SELECT 'CREATE USER my_user'
    WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec
    

    Workaround from the shell

    echo "SELECT 'CREATE USER my_user' WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec" | psql
    

    See accepted answer there for more details.

提交回复
热议问题