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

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

    The accepted answer suffers from a race condition if two such scripts are executed concurrently on the same Postgres cluster (DB server), as is common in continuous-integration environments.

    It's generally safer to try to create the role and gracefully deal with problems when creating it:

    DO $$
    BEGIN
      CREATE ROLE my_role WITH NOLOGIN;
      EXCEPTION WHEN DUPLICATE_OBJECT THEN
      RAISE NOTICE 'not creating role my_role -- it already exists';
    END
    $$;
    

提交回复
热议问题