import streamlit as st import re import json st.set_page_config(page_title="Databricks Grant Object Updater", layout="wide") st.title("Databricks Grant Object Name Changer") st.markdown("---") # ── Environment → catalog mapping ── CATALOG_MAP = { "dev": "uc_dev_apac_mdip_01", "qa": "uc_qa_apac_mdip_01", "prod": "uc_prod_apac_mdip_01", } # ── Predefined grant principals ── TABLE_GRANTS = [ ("SELECT, MODIFY", "Team.App.MDIP.Core.Team"), ("SELECT, MODIFY", "svciscpkpi@pepsico.com"), ("SELECT, MODIFY", "Team.App.MDIPAPAC.ISCP.KPI.NONPROD.Developer"), ("SELECT, MODIFY", "svcCViscpkrptprd@pepsico.com"), ("SELECT, MODIFY", "Team.App.PBNA.TDQKETSPROD.ADB"), ("SELECT, MODIFY", "Team.App.PBNA.TDQKETS.ADB"), ("SELECT, MODIFY", "Team.App.MDIPAPAC.ISCP.KPI.PROD.Reader"), ("SELECT, MODIFY", "Team.App.MDIPAPAC.ISCP.KPI.PROD.Executor"), ] VIEW_GRANTS = [ ("SELECT", "Team.App.MDIP.Core.Team"), ("SELECT", "svciscpkpi@pepsico.com"), ("SELECT", "Team.App.MDIPAPAC.ISCP.KPI.NONPROD.Developer"), ("SELECT", "svcCViscpkrptprd@pepsico.com"), ("SELECT", "Team.App.PBNA.TDQKETSPROD.ADB"), ("SELECT", "Team.App.PBNA.TDQKETS.ADB"), ("SELECT", "Team.App.MDIPAPAC.ISCP.KPI.PROD.Reader"), ("SELECT", "Team.App.MDIPAPAC.ISCP.KPI.PROD.Executor"), ] def resolve_full_name(name: str, catalog: str) -> str: """ Resolve a table/view identifier to a fully-qualified 3-part name. Rules (dot-count based): 1 dot → schema.object : {catalog}.{name} 2+ dots → already a full name : swap any uc__apac_mdip_01 prefix with the selected catalog """ parts = name.strip().split(".") if len(parts) == 2: return f"{catalog}.{name.strip()}" elif len(parts) >= 3: return re.sub(r'^uc_(dev|qa|prod)_apac_mdip_01', catalog, name.strip()) return name.strip() def build_table_grants(full_name: str) -> str: return "\n".join( f"GRANT {privs} ON TABLE {full_name} TO `{principal}`;" for privs, principal in TABLE_GRANTS ) def build_view_grants(full_name: str) -> str: return "\n".join( f"GRANT {privs} ON VIEW {full_name} TO `{principal}`;" for privs, principal in VIEW_GRANTS ) def create_databricks_notebook(sql_statements: str, title: str) -> str: """Create a .ipynb notebook compatible with Databricks import.""" cells = [] cells.append({ "cell_type": "markdown", "metadata": {}, "source": [f"# {title}\n", "\n", "Auto-generated GRANT scripts — run each cell or Run All.\n"] }) blocks = re.split(r'(?=-- ==========)', sql_statements.strip()) blocks = [b.strip() for b in blocks if b.strip()] for block in blocks: lines = block.split('\n') source_lines = [line + "\n" for line in lines] if source_lines: source_lines[-1] = source_lines[-1].rstrip("\n") cells.append({ "cell_type": "code", "metadata": {}, "source": source_lines, "outputs": [], "execution_count": None }) notebook = { "nbformat": 4, "nbformat_minor": 0, "metadata": { "application/vnd.databricks.v1+notebook": { "language": "sql", "notebookName": title, "notebookOrigID": 0 }, "kernelspec": {"display_name": "SQL", "language": "sql", "name": "sql"}, "language_info": {"name": "sql"} }, "cells": cells } return json.dumps(notebook, indent=2) # ── Environment selector ── environment = st.selectbox( "Select Environment:", options=["dev", "qa", "prod"], key="environment" ) catalog = CATALOG_MAP[environment] st.info(f"**Environment:** `{environment}` | **Catalog:** `{catalog}`") st.markdown("---") # ── Tabs ── tab_tables, tab_views = st.tabs(["TABLE Grants", "VIEW Grants"]) # ─────────────────────────── TABLE GRANTS ─────────────────────────── with tab_tables: st.markdown("### Predefined TABLE Grant Template") preview_table = "\n".join( f"GRANT {p} ON TABLE <{catalog}.schema.table_name> TO `{g}`;" for p, g in TABLE_GRANTS ) st.code(preview_table, language="sql") st.markdown("### Enter Table Names (one per line)") st.caption( "Accepted formats:\n" "- `SCHEMA.TABLE_NAME` → auto-expands to `{catalog}.SCHEMA.TABLE_NAME`\n" "- `uc__apac_mdip_01.SCHEMA.TABLE_NAME` → catalog is swapped to match selected env" ) table_names_input = st.text_area( "Table names:", height=150, key="table_names", placeholder=( f"uc_qa_apac_mdip_01.ISCP_P_DATA.AJDA_SP_TS_INVTRY_RPRT\n" f"uc_dev_apac_mdip_01.ISCP_P_DATA.ANOTHER_TABLE" ), ) if st.button("Generate TABLE Grant Scripts", key="btn_tables"): if not table_names_input.strip(): st.warning("Please enter at least one table name.") else: table_names = [t.strip() for t in table_names_input.strip().splitlines() if t.strip()] all_scripts = [] for name in table_names: full_name = resolve_full_name(name, catalog) block = f"-- ========== {full_name} ==========\n{build_table_grants(full_name)}" all_scripts.append(block) combined = "\n\n".join(all_scripts) st.markdown("### Generated TABLE Grant Scripts") st.code(combined, language="sql") st.success(f"Generated grant scripts for {len(table_names)} table(s) in **{environment}** environment!") st.session_state["table_combined"] = combined if "table_combined" in st.session_state: nb = create_databricks_notebook(st.session_state["table_combined"], "Table_Grant_Scripts") st.download_button( label="Download as .ipynb (Databricks Notebook)", data=nb, file_name="table_grant_scripts.ipynb", mime="application/x-ipynb+json", key="dl_tables", ) # ─────────────────────────── VIEW GRANTS ──────────────────────────── with tab_views: st.markdown("### Predefined VIEW Grant Template") preview_view = "\n".join( f"GRANT {p} ON VIEW <{catalog}.schema.view_name> TO `{g}`;" for p, g in VIEW_GRANTS ) st.code(preview_view, language="sql") st.markdown("### Enter View Names (one per line)") st.caption( "Accepted formats:\n" "- `SCHEMA.VIEW_NAME` → auto-expands to `{catalog}.SCHEMA.VIEW_NAME`\n" "- `uc__apac_mdip_01.SCHEMA.VIEW_NAME` → catalog is swapped to match selected env" ) view_names_input = st.text_area( "View names:", height=150, key="view_names", placeholder=( f"uc_qa_apac_mdip_01.ISCP_P_DATA.SOME_VIEW\n" f"uc_dev_apac_mdip_01.ISCP_P_DATA.ANOTHER_VIEW" ), ) if st.button("Generate VIEW Grant Scripts", key="btn_views"): if not view_names_input.strip(): st.warning("Please enter at least one view name.") else: view_names = [v.strip() for v in view_names_input.strip().splitlines() if v.strip()] all_scripts = [] for name in view_names: full_name = resolve_full_name(name, catalog) block = f"-- ========== {full_name} ==========\n{build_view_grants(full_name)}" all_scripts.append(block) combined = "\n\n".join(all_scripts) st.markdown("### Generated VIEW Grant Scripts") st.code(combined, language="sql") st.success(f"Generated grant scripts for {len(view_names)} view(s) in **{environment}** environment!") st.session_state["view_combined"] = combined if "view_combined" in st.session_state: nb = create_databricks_notebook(st.session_state["view_combined"], "View_Grant_Scripts") st.download_button( label="Download as .ipynb (Databricks Notebook)", data=nb, file_name="view_grant_scripts.ipynb", mime="application/x-ipynb+json", key="dl_views", )