This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing a script which we can use for changing ownership of all objects in PostgreSQL.
Why ownership of object needs to change?
I have created one application user for our production PostgreSQL database.
But system admin and deployment manager made one mistake and executed objects with some another database user.
After deployment, we came to know that objects were not deployed under proper ownership.
Now we have 2500 tables, 450 views and 230 stored functions are required to change their ownership.
Now, I need to solve this by using only one script because of manual changing ownership of this many objects will take too much time.
Below is my demonstration:
Let’s First, create one function with $parameter value so that you can use this function as a template.
1 2 3 4 5 6 7 8 |
CREATE OR REPLACE FUNCTION ChangeObjectsOwnerShip(text) returns text language plpgsql volatile AS $f$ BEGIN EXECUTE $1; RETURN $1; END; $f$; |
Now generate two select statements to get the alter script.
Below select statement is for Tables, Sequences and Views.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
SELECT ChangeObjectsOwnerShip ( 'ALTER TABLE ' || quote_ident(s.nspname) || '.' ||quote_ident(s.relname) || ' owner TO app_user' ) FROM ( SELECT nspname ,relname FROM pg_class c JOIN pg_namespace n ON (c.relnamespace = n.oid) WHERE nspname NOT LIKE E'pg\\_%' AND nspname <> 'information_schema' AND relkind IN ('r','S','v') ORDER BY relkind = 'S' )s; |
Below select statement is for all functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
SELECT ChangeObjectsOwnerShip ( 'ALTER FUNCTION ' || quote_ident(s.nspname) || '.' ||quote_ident(s.function_name) || '('||s.parms||') owner TO app_user' ) FROM ( SELECT nspname ,proname AS function_name , pg_catalog.oidvectortypes(proargtypes) AS parms FROM pg_catalog.pg_proc AS c JOIN pg_namespace n ON (c.pronamespace = n.oid) WHERE nspname != 'information_schema' AND nspname NOT LIKE E'pg\\_%' ORDER BY proname )s; |
In above code, preparing one alter statement to change ownership for all objects from assign user to mentioned ” app_user “. You can change ” app_user ” by your require user name.
After executing above select statements, you can find all alter scripts in a result.
Copy this result and execute above alter scripts using super user.
All ownership will be changed after executing this alter the script.