Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def update_grants(
- schema: str,
- role_configs: dict,
- **kwargs
- ):
- """
- Обновляет права доступа для заданной схемы и списка ролей.
- :param schema: Имя схемы.
- :param role_configs: Словарь с конфигурацией для ролей, где ключ — имя роли,
- а значение — словарь с параметрами:
- - "include_tables": список таблиц, на которые выдаются права.
- - "exclude_tables": список таблиц, исключаемых из прав.
- - "exclude_columns": словарь { "table_name": ["column1", "column2"] }
- с исключаемыми столбцами.
- """
- with PostgresHook(postgres_conn_id="DWH_prod").get_conn() as conn:
- cur = conn.cursor()
- for role, config in role_configs.items():
- include_tables = config.get("include_tables", [])
- exclude_tables = config.get("exclude_tables", [])
- exclude_columns = config.get("exclude_columns", {})
- # 1. Общий доступ для роли на схему
- cur.execute(f"GRANT USAGE ON SCHEMA {schema} TO {role};")
- # 2. Условная выдача прав на таблицы
- if include_tables:
- for table in include_tables:
- grant_query = f"GRANT SELECT ON {schema}.{table} TO {role};"
- logging.info(grant_query)
- cur.execute(grant_query)
- else:
- # Если include_tables не задан, выдать права на все таблицы, кроме исключенных
- cur.execute(f"GRANT SELECT ON ALL TABLES IN SCHEMA {schema} TO {role};")
- if exclude_tables:
- query_revoke = f"""
- WITH tables_to_revoke AS (
- SELECT table_schema, table_name
- FROM information_schema.tables
- WHERE table_schema = %s AND table_name = ANY(%s)
- )
- SELECT 'REVOKE SELECT ON ' || table_schema || '.' || table_name || ' FROM {role};'
- FROM tables_to_revoke;
- """
- cur.execute(query_revoke, (schema, exclude_tables))
- revoke_statements = cur.fetchall()
- for row in revoke_statements:
- logging.info(row[0])
- cur.execute(row[0])
- # 3. Выдача прав на определенные столбцы
- if exclude_columns:
- for table, columns in exclude_columns.items():
- columns_to_grant = f"""
- SELECT column_name
- FROM information_schema.columns
- WHERE table_schema = %s AND table_name = %s
- AND column_name NOT IN %s;
- """
- cur.execute(columns_to_grant, (schema, table, tuple(columns)))
- granted_columns = cur.fetchall()
- if granted_columns:
- column_list = ", ".join(col[0] for col in granted_columns)
- grant_query = (
- f"GRANT SELECT ({column_list}) ON {schema}.{table} TO {role};"
- )
- logging.info(grant_query)
- cur.execute(grant_query)
- conn.commit()
- cur.close()
Advertisement
Add Comment
Please, Sign In to add comment