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

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

    My team was hitting a situation with multiple databases on one server, depending on which database you connected to, the ROLE in question was not returned by SELECT * FROM pg_catalog.pg_user, as proposed by @erwin-brandstetter and @a_horse_with_no_name. The conditional block executed, and we hit role "my_user" already exists.

    Unfortunately we aren't sure of exact conditions, but this solution works around the problem:

            DO  
            $body$
            BEGIN
                CREATE ROLE my_user LOGIN PASSWORD 'my_password';
            EXCEPTION WHEN others THEN
                RAISE NOTICE 'my_user role exists, not re-creating';
            END
            $body$
    

    It could probably be made more specific to rule out other exceptions.

提交回复
热议问题