How to alter the ownership of some tables inside a database from postgres to another user?

╄→гoц情女王★ 提交于 2020-04-16 05:54:28

问题


I have a database which contains significant number of tables. Some of the tables are owned by postgres user and not the one I created. I want to transfer the ownership of such tables to the one I created,because when doing django-migrations, you can only set one user and password for the psql connection and that user doesnt have access to the tables owned by the postgres user, thus the migrations are not completed.

So far, googling didn't help as they suggest either using ALTER or REASSIGN OWNED to change the ownership of the database or the table. But the problem is that these cannot change the ownership of some of the tables as they are required to be owned by postgres. I can manually change the ownership by selecting each table one by one, but when trying to do altogether,I get an error saying

"ERROR: cannot reassign ownership of objects owned by role postgres because they are required by the database system".

Manually changing more than a hundred tables is not an option. Does anyone have any workaround idea for this issue?


回答1:


Have you tried with an anonymous code block? This code block below selects all tables from the schema public that belongs to the user postgres and set the ownership to the user user:

DO $$
DECLARE row RECORD;
BEGIN
  FOR row IN SELECT * FROM pg_tables 
    WHERE schemaname = 'public' AND tableowner = 'postgres'
    LOOP EXECUTE 'ALTER TABLE ' || row.tablename || ' OWNER TO user';
  END LOOP;
END;
$$;

Keep in mind that this operation will modify the ownership of all tables in your schema that belongs to the given user. Obviously you can further filter these tables by changing the pg_tables query in the loop. Take a look at:

SELECT * FROM pg_tables WHERE schemaname = 'public' AND tableowner = 'postgres';

Use it with care!

EDIT: To filter out a few tables from the selection above add a NOT IN, such as:

SELECT * FROM pg_tables 
WHERE schemaname = 'public' AND tableowner = 'postgres'
AND tablename NOT IN ('table1','table2','table3')


来源:https://stackoverflow.com/questions/59785733/how-to-alter-the-ownership-of-some-tables-inside-a-database-from-postgres-to-ano

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!