Skip to content

Instantly share code, notes, and snippets.

@Cediddi
Created July 28, 2016 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cediddi/e3ed3fcd66555545b8f0fc7ddb32c465 to your computer and use it in GitHub Desktop.
Save Cediddi/e3ed3fcd66555545b8f0fc7ddb32c465 to your computer and use it in GitHub Desktop.
I needed a way to bulk alter ownerships to another user. This worked for me very well. Usage: ./pg_change_ownership dbname username
#!/usr/bin/env bash
dbname=$1
dbuser=$2
psql -c "alter database \"$dbname\" owner to \"$dbuser\"" $dbname;
for tbl in `psql -qAt -c "select tablename from pg_tables where schemaname = 'public';" $dbname`;
do
psql -c "alter table \"$tbl\" owner to \"$dbuser\"" $dbname;
done
for tbl in `psql -qAt -c "select sequence_name from information_schema.sequences where sequence_schema = 'public';" $dbname`;
do
psql -c "alter table \"$tbl\" owner to \"$dbuser\"" $dbname;
done
for tbl in `psql -qAt -c "select table_name from information_schema.views where table_schema = 'public';" $dbname`;
do
psql -c "alter table \"$tbl\" owner to \"$dbuser\"" $dbname;
done
for tbl in `psql -qAt -c "select matviewname from pg_catalog.pg_matviews where schemaname = 'public';" $dbname`;
do
psql -c "alter materialized view \"$tbl\" owner to \"$dbuser\"" $dbname;
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment