Postgre change ownership of whole database to the role/user (including tables, functions, and views)

If you need to transfer ownership of whole database (in postgress) you need to alter all tables, sequnces, views, and materialized views separately.

Below is script generets it's for you. Just type in the my.vars.new_owner name of the role to which you want to transfer ownerships.

set session my.vars.new_owner = 'new_owner_role';

select current_setting('my.vars.new_owner');

alter database {database_name} owner to current_setting('my.vars.new_owner');

SELECT 'ALTER TABLE ' || schemaname || '."' || tablename || '" OWNER TO ' || current_setting('my.vars.new_owner') || ';'
FROM pg_tables
WHERE NOT schemaname IN ('pg_catalog', 'information_schema')
ORDER BY schemaname, tablename;

SELECT 'ALTER SEQUENCE ' || sequence_schema || '."' || sequence_name || '" OWNER TO ' || current_setting('my.vars.new_owner') || ';'
FROM information_schema.sequences
WHERE NOT sequence_schema IN ('pg_catalog', 'information_schema')
ORDER BY sequence_schema, sequence_name;

SELECT 'ALTER VIEW ' || table_schema || '."' || table_name || '" OWNER TO ' || current_setting('my.vars.new_owner') || ';'
FROM information_schema.views
WHERE NOT table_schema IN ('pg_catalog', 'information_schema')
ORDER BY table_schema, table_name;

SELECT 'ALTER TABLE ' || oid::regclass::text || ' OWNER TO ' || current_setting('my.vars.new_owner') || ';'
FROM pg_class
WHERE relkind = 'm'
ORDER BY oid;

Read more

Missing foreign keys finder

Sometimes when you need to import big bunch of data you may need to consider setting a flag: SET session_replication_role = 'replica'; However, this import,

Extend »

Usefull PostgreSQL commands

Source : https://gist.github.com/rgreenjr/3637525 — show running queries (pre 9.2) SELECT procpid, age(clock_timestamp(), query_start), usename, current_query FROM pg_stat_activity WHERE current_query != '<IDLE>' AND current_query NOT ILIKE

Extend »
Scroll to Top