Say, that database "foo" is now owned by "user1"
Alter owner:
\c postgres
ALTER DATABASE "foo" OWNER TO "user2"
Reassign ownership (see also https://stackoverflow.com/a/13535184/1943126):
note: this will affect objects in current database ("foo") but also shared objects (databases,tablespaces)!!!
\c "foo"
REASSIGN OWNED BY "user1" TO "user2"
note: the following is probably not needed, covered by re-assignment of ownership
Revoke existing permissions from previous owner on all available schemas:
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM "user1";
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA "bar" FROM "user1";
REVOKE USAGE ON SCHEMA "bar" FROM "user1";
Grant permissions on new owner:
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "user2";
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA "bar" TO "user2";
GRANT USAGE ON SCHEMA "bar" TO "user2"
Check existing permissions on tables:
SELECT grantor, grantee, table_schema, table_name,privilege_type FROM information_schema.table_privileges
REASSIGN OWNED BY old_role [, ...] TO new_role
This changes all objects owned by old_role to the new role. You don't have to think about what kind of objects that the user has, they will all be changed.
Note that it only applies to objects inside a single database. It does not alter the owner of the database itself either.
It is available back to at least 8.2. Their online documentation only goes that far back.
------单个DB 不是所有 REASSIGN OWNED BY doesn't work for objects owned by postgres.
Just to be clear, this command works in the database that you are currently connected ONLY. If the old_role owns objects in multiple databases, you should connect and run this command in each one of those databases
Since you're changing the ownership for all tables, you likely want views and sequences too. Here's what I did:
Tables:
for tbl in `psql -qAt -c "select tablename from pg_tables where schemaname = 'public';" YOUR_DB` ; do psql -c "alter table \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done
Sequences:
for tbl in `psql -qAt -c "select sequence_name from information_schema.sequences where sequence_schema = 'public';" YOUR_DB` ; do psql -c "alter sequence \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done
Views:
for tbl in `psql -qAt -c "select table_name from information_schema.views where table_schema = 'public';" YOUR_DB` ; do psql -c "alter view \"$tbl\" owner to NEW_OWNER" YOUR_DB ; done
You could probably DRY that up a bit since the alter statements are identical for all three