title: Drop USER (with privileges) IF EXIST in Postgres
body: <p>I need to conditionally drop a user (if it does not already not exists) in Postgres. DROP USER IF EXIST is fine but according to the documentation, I also need to remove privileges first, however either DROP OWNED or REVOKE seem to have conditional IF EXIST clauses. How Can I conditionally remove privileges from my user?</p>
  
  <p>My database is Postgres v9.6</p>
  
  <p>Background:</p>
  
  <p>I am trying to create a set of setup/teardown scripts for Postgres that will create a test area for a bunch of functions. The setup script should:</p>
  
  <ul>
  <li>Create a user (if it does not already exist)</li>
  <li>Create a schema with some tables (if not already exist)</li>
  </ul>
  
  <p>and teardown will:</p>
  
  <ul>
  <li>Drop the user (if it exists)</li>
  <li>Drop the schema (if it exists)</li>
  </ul>
  
  <p>The thing is that the test suite can be interrupted and leave the database/test area in a corrupt state (eg if teardown was never executed) so I have to account for that in my scripts.</p>
  
  <p>According to the documentation for Postgres: </p>
  
  <blockquote>
    <p>A role cannot be removed if it is still referenced in any database of the cluster; an error will be raised if so. Before dropping the role, you must drop all the objects it owns (or reassign their ownership)</p>
  </blockquote>
  
  <p>My user has one privilege, namely CONNECT to my test database where my test schema lies. This is because I am planning to login using the test user and execute the tests.</p>
  
  <p>But because there doesn't seem to be any conditional clauses on either DROP OWNED BY or REVOKE, I cant see how that could be done?</p>