Last active
August 18, 2021 22:12
-
-
Save ipmb/bf176278e1a37d07efd9f7b62927cab5 to your computer and use it in GitHub Desktop.
change ownership of all items in public schema using Python/psycopg2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import psycopg2 | |
NEW_USER = "fred" | |
types = {"c": "TABLE", "t": "TABLE", "r": "TABLE", "S": "SEQUENCE", "i": "INDEX", "v": "VIEW"} | |
with psycopg2.connect(**kwargs) as conn: | |
conn.autocommit = True | |
with conn.cursor() as curs: | |
for kind, name in types.items(): | |
curs.execute( | |
f"SELECT format('ALTER {name} %%I.%%I OWNER TO %%I', n.nspname, c.relname, %s) " | |
"FROM pg_class c, pg_namespace n " | |
"WHERE n.oid = c.relnamespace AND n.nspname = 'public' AND c.relkind = %s", | |
(NEW_USER, kind), | |
) | |
for s in curs.fetchall(): | |
print(f" + {s[0]}") | |
curs.execute(s[0]) | |
# Functions | |
curs.execute( | |
"SELECT format('ALTER FUNCTION %%I.%%I(%%I) OWNER TO %%I', p.proname, n.nspname, pg_catalog.pg_get_function_identity_arguments(p.oid), %s) " | |
"FROM pg_catalog.pg_namespace n " | |
"JOIN pg_catalog.pg_proc p ON p.pronamespace = n.oid " | |
"WHERE n.nspname = 'public'", | |
(NEW_USER,), | |
) | |
for s in curs.fetchall(): | |
print(f" + {s[0]}") | |
curs.execute(s[0]) | |
# Text Search Dictionaries | |
curs.execute( | |
f"SELECT format('ALTER TEXT SEARCH DICTIONARY %%I.%%I OWNER TO %%I', n.nspname, d.dictname, %s) " | |
"FROM pg_catalog.pg_namespace n " | |
"JOIN pg_catalog.pg_ts_dict d ON d.dictnamespace = n.oid " | |
"WHERE n.nspname = 'public'", | |
(NEW_USER,), | |
) | |
for s in curs.fetchall(): | |
print(f" + {s[0]}") | |
curs.execute(s[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A pure SQL version