@contextlib.contextmanager
def db_role_setter(conn, *, role_name):
    'Since we catch exceptions here and log, temporarily install a customised hook.'
    with conn.cursor() as cursor:
        cursor.execute('SHOW ROLE')
        old_role = cursor.fetchone()[0]
        cursor.execute('SET ROLE %s', [role_name])
        (yield role_name)
        cursor.execute('SET ROLE %s', [old_role])
Since we catch exceptions here and log, temporarily install a customised hook.
@contextlib.contextmanager
def db_role_setter(conn, *, role_name):
    
    with conn.cursor() as cursor:
        cursor.execute('SHOW ROLE')
        old_role = cursor.fetchone()[0]
        cursor.execute('SET ROLE %s', [role_name])
        (yield role_name)
        cursor.execute('SET ROLE %s', [old_role])